user585440
user585440

Reputation:

How to get check status for check box in jquery

I have a check box as follow.

<input id='showDeletedQuestionsId' name='showDeletedQuestions' type='checkbox' style='margin-right: 3px' />""

I want to know if it is checked in jquery. The code is:

    var showDeletedCheckbox = $('#showDeletedQuestions').is(':checked');

However, I notice that it always returns false even if check box is checked. I'd like to know how to get the check status in jquery.

Upvotes: 0

Views: 82

Answers (3)

guradio
guradio

Reputation: 15555

<input id='showDeletedQuestionsId' name='showDeletedQuestions' type='checkbox' style='margin-right: 3px' />

js

var showDeletedCheckbox = $('#showDeletedQuestions').is(':checked');

your id are not matching match them and it will work

$('#showDeletedQuestionsId').change(function () {
    var showDeletedCheckbox = $('#showDeletedQuestionsId').is(':checked');

    if (showDeletedCheckbox) {
        alert('checked')
    } else {
        alert('not checked')
    }
})

demo

Upvotes: 3

Rohit Batta
Rohit Batta

Reputation: 482

There is a mistake in your code. "#" selector is used for Id field only. but you have used "name" attribute in selection. Modify your code as below, it will work..

var showDeletedCheckbox = $('#showDeletedQuestionsId').is(':checked');

For reference check this link

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You are not using ID correctly, showDeletedQuestionsId is defined and showDeletedQuestions is used

use

var showDeletedCheckbox = $('#showDeletedQuestionsId').is(':checked');

As an alternative you can use .prop()

var showDeletedCheckbox = $('#showDeletedQuestionsId').prop('checked');

Upvotes: 3

Related Questions