robsn84 robsn84 - 1 month ago 5
jQuery Question

hide/show php checkbox by id like www.anysite.php?id=10

I have a form and a checkbox. By click on the checkbox, a div within some other divs will show up or hide. This works! But, if i visit my page with an id like xxxxx.php?id=10, the checkbox is checked but the divs are hide. if i click on the checkbox, the divs will show up, but the checkbox is unchecked (bad for e.g. mysql updates).. hope anyone can help me by this issue..

Here my code:



$(document).ready(function() {
$('#Show').hide();
$("input[name=mycheckbox]").click(function () {
$('#Show').toggle();
});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="form">
<div class="form-group">
<div class="form-group">
<div class="checkbox-inline">
<label>
<input type="checkbox" name="mycheckbox" id="mycheckbox" value="yes"> my option
</label>
</div>
</div>

</div>
<div id="Show">
<div class="form-group">
<label for="textinput" class="control-label">Company </label>
<div class="">
<input type="text" class="form-control" name="name" id="name" placeholder="" value="">
</div>
</div>
</div>
</form>





My input field have this code (php doesn't work in the snippet):

<input type="checkbox" name="mycheckbox" id="mycheckbox" value="yes" <?php if (isset($_GET['id'])) {echo $row->mycheckbox == "yes" ? 'checked="checked"' : "";}?>


thanks for your help!

Answer

I would recommend to use change event, trigger using .trigger('change') on page load so that the div in sync with the state of checkbox element.

Also you should .toggle(display)

$("input[name=mycheckbox]").change(function () {
   $('#Show').toggle(this.checked);
}).trigger('change');
Comments