Ryre
Ryre

Reputation: 6181

Checkbox irregularities with jQuery

Here's some html:

<form>
    <input type="checkbox" id="check-123" />
    <input type="text" id="text-123" onchange="doSomething('123')" />
</form>

And here's some javascript:

function doSomething(key)
{
    var textbox = $('#text-'+key);
    var checkbox = $('#check-'+key);
    checkbox.attr('checked',(textbox.val()!="") );
}

My goal here is to check the checkbox anytime there's a value in the text box, and uncheck when that value is removed. This appears to work fine in the html (I can see checked="checked" being added to the checkbox), but the checkbox only appears checked the first time something is entered in the textbox.

Why would a checkbox show unchecked even if checked="checked" was added to the html?

Upvotes: 0

Views: 58

Answers (3)

Justin Bicknell
Justin Bicknell

Reputation: 4808

I've seen some funny things with the checked attribute in IE8 and lower. In some cases I've had to set both the property and the attribute, even though modern browsers seem to be okay with just adjusting the property:

checkbox.prop('checked',textbox.val()!="");//property

Note, the following is only necessary if you come across any browser related inconsistencies.

if(textbox.val()!="") 
{
    checkbox.attr('checked','checked');
}
else
{
    checkbox.removeAttr('checked');
}

Upvotes: 2

Musa
Musa

Reputation: 97717

Use element properties rather than attributes to change their state via javascript

checkbox.prop('checked',(textbox.val()!="") );

From the jQuery docs on .attr() and .prop():

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

The emphasis is jQuery's own. Only the checked property will reflect and control the checkbox's current state. The checked attribute shouldn't be used to control the checkbox state.

Upvotes: 6

RobG
RobG

Reputation: 147513

consider something like:

function doSomething(el) {
    el.form['check-' + el.name.split('-')[1]].checked = !!el.value;
}


<form>
    <input type="checkbox" name="check-123">
    <input type="text" name="text-123" onchange="doSomething(this)">
</form>

Upvotes: 2

Related Questions