user2341923
user2341923

Reputation: 4727

jQuery .first() – does not work with IE?

The following code adds a cell with a radiobutton to each row of a table and checks the first one:

$(document).ready(function () {
    $('tr').prepend('<td>');
    $('<input name="delete" type="radio"/>')
        .prependTo('tbody td:first-child')
        .first().attr('checked', true);
});

It does not check the first radiobutton with IE 11, jquery-2.1.4 but works properly with FireFox, Chrome and MS Edge; function last() works for IE in this case as expected. Is it a bug?

Upvotes: 1

Views: 392

Answers (2)

Guffa
Guffa

Reputation: 700630

You are settings the checked attribute to "true" instead of "checked", which only works for browsers that choose to inpret that as a value that means "checked". Also, as the attribute is the initial value of the input, it doesn't always work after the element is created.

You want to set the current value instead of the initial value, which is the checked property instead of the checked attribute. Use the prop method to set the checked property to true:

$(document).ready(function () {
    $('tr').prepend('<td>');
    $('<input name="delete" type="radio"/>')
        .prependTo('tbody td:first-child')
        .first().prop('checked', true);
});

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075159

Nothing to do with first; it's to do with what you're doing with the first one.

When using true/false with checked, you want to use the property, not the attribute. jQuery used to jump through a lot of hoops to set properties/attributes for people reliably cross-browser when they used attr with boolean properties, but many of those hoops were removed (and only some added back) when they added prop in v1.6.

If you use prop, it works on IE11, too:

$(document).ready(function () {
    $('tr').prepend('<td>');
    $('<input name="delete" type="radio"/>')
        .prependTo('tbody td:first-child')
        .first().prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<table>
    <tbody>
        <tr></tr>
        <tr></tr>
        <tr></tr>
        <tr></tr>
    </tbody>
</table>

Just for completeness: If you did want to use the attribute, the specification requires that the attribute must be removed/absent for the flag not to be set, and must be either "" or the name of the attribute ("checked", in this case) for it to be set:

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Note: The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

Upvotes: 2

Related Questions