1

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.

2
  • I just put the checkbox in the snippet and closed your DOM ready handler, and it seems to work just fine? Commented Jul 22, 2017 at 10:06
  • You have better to use var checkedState = $("input.select-item").prop("checked"); or var checkedState = $("input.select-item").is(":checked");. And if you want to get checked/uncheck strings, you can use: var checkedState = $("input.select-item").is(":checked") ? "checked" : "uncheck"; BUT passing boolean instead (true or false) seems more legit Commented Jul 22, 2017 at 10:09

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.