I have dynamically generated checkbox within dynamically generated row. I attach delegated event ('click') listener to the entire row.
And everything works perfectly fine - I toggle checkbox status by clicking any place within the row, except just one little thing - clicking checkbox itself does not toggle its status.
Below is my sample code. Any ideas?
//Generate dynamically div row encompassing checkbox and label
$('#wraper').append(`
<div id="row">
<label>This is the checkbox</label>
<input type="checkbox"></input>
</div>
<br>
<span class="msg"></span>
`);
//Attach delegated event listener to entire row
$('#wraper').on('click', '#row', function(){
//Toggle checked attribute
$('#row [type="checkbox"]').get(0).checked = !$('#row [type="checkbox"]').get(0).checked;
//Display checked status after click
$('#wraper .msg').text(`Checkbox status is ${$('#row [type="checkbox"]').get(0).checked}`);
});
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div id="wraper"></div>
</body>
</html>
As mentioned in the comments, remove the
click
logic from your code. It's immediately overwriting the default HTML functionality. If your intention is to get the checkbox checked even when the label is clicked, you can use thefor
attribute and point to the checkbox'sid
:Update: If you want to the checkbox checked anywhere from the parent
div
, then add aclick
handler to the parent. If the click target is not acheckbox
, force the checkbox to be checked. If the target is acheckbox
, don't do anything.