Reputation: 2941
I have a textbox
, a checkbox and a span
tag. When I click on the checkbox, it should show its state in the span
tag. When textbox
is updated, it reinserts the checkbox block. When you click on the checkbox now, it fails to update the state.
I am using the on
event handler for checkbox click event, so I expect it to work.
Any idea why this is not working as expected?
$('div[role] input[type=checkbox]').on('click', chg);
$('div[role] input[type=text]').on('input', sourceChanged);
function chg() {
var istiki = $(this).is(":checked");
$('#upd').html(istiki);
}
function sourceChanged() {
$('span', $(this).closest('.input-group')).html('<input type="checkbox">');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div role="Tiki" class="input-group">
<input type="text" class="form-control" />
<span class="input-group-addon"><input type="checkbox" /></span>
</div>
<span id="upd"></span>
Upvotes: 1
Views: 74
Reputation: 128781
As you're dynamically creating a new checkbox when the value changes, you need to delegate the event to your checkbox by assigning it to a non-dynamic ancestor:
$('div[role]').on('change', 'input[type=checkbox]', chg);
Note how I've used change
instead of click
as this is more appropriate for checkboxes.
In the below snippet I've also changed $(this).is(":checked")
to just this.checked
.
$('div[role]').on('change', 'input[type=checkbox]', chg);
$('div[role] input[type=text]').on('input', sourceChanged);
function chg() {
var istiki = this.checked;
$('#upd').html(istiki);
}
function sourceChanged() {
$('span', $(this).closest('.input-group')).html('<input type="checkbox">');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div role="Tiki" class="input-group">
<input type="text" class="form-control" />
<span class="input-group-addon"><input type="checkbox" /></span>
</div>
<span id="upd"></span>
Note also that if you want it to say false
you should convert your istiki
variable to a string:
$('#upd').html('' + isticki);
Upvotes: 2