AlexGH
AlexGH

Reputation: 2805

Check if checkbox is checked using next() in JQuery

I need to check if a checkbox next to a textbox is checked or not, but the result I'm getting from that condition in my code is always true, so that's wrong.

I've made some tests using the next() method from jQuery. I'm pointing to the next checkbox close to the textbox, which is working fine.

This code is always returning true, whether the checkbox is checked or not:

if ($(this).next('.isFileSelected:checkbox:checked')) {
    //do some other stuff...
}

I tried these changes too, but I'm getting the same results:

if ($(this).next('input:checkbox:checked')) {
    //do some other stuff...
}

How can I accomplish this using jQuery or pure JavaScript code?

Upvotes: 0

Views: 744

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42304

You're looking for the prop() attribute checked:

if ($(this).next('.isFileSelected:checkbox').prop('checked')) {
  // Checked
}

Or, alternatively, you can use .is() to check for the :checked pseudo-selector:

 if ($(this).next('.isFileSelected:checkbox').is(":checked")) {
  // Also Checked
}   

Hope this helps! :)

Upvotes: 4

Related Questions