Reputation: 2913
So I have a html for with 9 checkboxes. I am trying to use JQuery to check when they have been checked/toggled. This is my current code.
<script>
$(document).ready(function(){
$("input[type=checkbox]").change(function() {
alert("Checked");
});
});
</script>
And here is my html setup:
<form method="post">
<input type="checkbox" id="1" name="1"/>
<label for="1"><span>1</span></label>
<input type="checkbox" id="2" name="2"/>
<label for="2"><span>2</span></label>
<input type="checkbox" id="3" name="3"/>
<label for="3"><span>3</span></label>
<input type="checkbox" id="4" name="4"/>
<label for="4"><span>4</span></label>
<input type="checkbox" id="5" name="5"/>
<label for="5"><span>5</span></label>
<input type="checkbox" id="6" name="6"/>
<label for="6"><span>6</span></label>
<input type="checkbox" id="7" name="7"/>
<label for="7"><span>7</span></label>
<input type="checkbox" id="8" name="8"/>
<label for="8"><span>8</span></label>
<input type="checkbox" id="9" name="9"/>
<label for="9"><span>9</span></label>
</form>
The above code has no alert output. What is wrong?
Upvotes: 0
Views: 88
Reputation: 94429
Use the attribute
selector and the :checked
selector to obtain the inputs. Then iterate through the checked inputs using .each()
$("input[type='checkbox']:checked").each(function(i,e){
alert(e.id);
});
JS Fiddle: http://jsfiddle.net/YyP4E/
Upvotes: 0
Reputation: 4081
Try this
$(document).ready(function() {
$("input[type='checkbox']").change(function() {
if($(this).is(":checked")) {
alert("Checked");
}
});
});
Upvotes: 0
Reputation: 57105
$(document).ready(function () {
$("input[type=checkbox]").change(function () {
var x = (this.checked) ? 'checked' : 'unchecked';
alert(x);
});
});
or
$(document).ready(function () {
$("input[type=checkbox]").change(function () {
if(this.checked){
alert('checked');
}
});
});
Upvotes: 0
Reputation: 27845
do it like
$(document).ready(function(){
$("input[type=checkbox]").click(function() {
if($(this).prop("checked"))
alert("Checked");
});
});
Here is a demo fiddle
Upvotes: 2