Skip to content Skip to sidebar Skip to footer

Why Does Order Of Defining Attributes For A Dynamically Created Checkbox In Jquery Affect Its Value?

I have this code in a js file: function buildRolePicker() { var pnl = $('[id$='staffRoles']'); $.each(roles['ContactGroupRoles'], function(iteration, item) { pnl.ap

Solution 1:

It seems that for whatever reason, IE (IE8 at least) and Opera don't retain the value attribute (though Chrome/Firefox do) through changing the type. Here's a simplified test:

$(document.body).append(
    $("<input />").attr({
        value: 'Test',
        type: 'checkbox'
    })
);
alert($("input").val());
alert(document.body.innerHTML);

You can try it here

IE8/Opera alerts:

  • "on"
  • <input type="checkbox">

Chrome/Firefox alerts:

  • "Test"
  • <input type="checkbox" value="Test">

I'm not sure why Opera in particular is behaving this way, but in any case...just attempting to better demonstrate the issue, the solution of course is to keep the type attribute first. Perhaps a future jQuery release will process type first in the loop, though if the <input> was defined with any attributes earlier this still wouldn't do much good.

However, the $("<input />", { value: 'Test', type: 'checkbox' }); format suffers the same problem, IMO this should be fixed.

Post a Comment for "Why Does Order Of Defining Attributes For A Dynamically Created Checkbox In Jquery Affect Its Value?"