Reputation: 4622
I have a table with a checkbox column - when you click the checkbox it performs a script that includes an AJAX request. I'm trying to set the checked state into a variable so I can then include this as a parameter in the AJAX POST request but I'm not able to get this into a variable so far.
Here's my checkbox input field with the script that is simplified to just capture the checked state of the input in the checkedState
variable:
$(document).ready(function() {
$("input.select-item").click(function() {
var productID = $(this).val();
var checkedState = $("input.select-item").attr("checked");
console.log(checkedState);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<td id="AT36288"><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36288" /></td>
So if the checkbox was not checked and the user checks this I would like to capture the value of "checked" in the variable, and if the checkbox was checked and the user unchecked this I would like to capture the value of "uncheck" in the variable. I'm getting an undefined
result for the variable in the console.
Upvotes: 1
Views: 2382
Reputation: 12085
1st : you need to use is checked $(this).is(":checked")
2nd : you need to use $(this)
instead of $("input.select-item").attr("checked")
because you need to refer the currently clicked
element instead of class name
$("input.select-item")
.
$(document).ready(function() {
$("input.select-item").click(function() {
var productID = $(this).val();
var checkedState = $(this).is(":checked");
console.log(checkedState);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<td id="AT36288"><input type="checkbox" class="select-item checkbox" name="select-item" value="AT36288" /></td>
Upvotes: 2
Reputation: 128
Hi the checkboxes and radioboxes events can be tracked better by change event. In jQuery you can check the status of the input field by following: $("input.select-item").is(":checked") or simply $(".select-item").is(":checked") Hope this helps.
Upvotes: 1