Why does the order in which attributes are defined for a dynamically created checkbox in jquery affect its value?

I have this code in js file:

function buildRolePicker() {
    var pnl = $("[id$='staffRoles']");
    $.each(roles["ContactGroupRoles"], function(iteration, item) {
        pnl.append(
                $(document.createElement("input")).attr({
                    id: 'cgr' + item['RoleId'],
                    name: 'cgroles',
                    value: item['RoleId'],
                    title: item['RoleName'],
                    type: 'checkbox'
                })
        );
        pnl.append(
                $(document.createElement('label')).attr({
                    'for': 'cgr' + item['RoleId']
                })
                .text(item['RoleName'])
        );
    });

    alert(document.forms[0].cgroles[8].value);
}

I wasted time in other sections of the code, trying to understand why the call

alert(document.forms[0].cgroles[8].value);

returned the value "on" when it should return a long one. Turns out the problem is the order in which the attributes are defined. If I change this:

            $(document.createElement("input")).attr({
                id: 'cgr' + item['RoleId'],
                name: 'cgroles',
                value: item['RoleId'],
                title: item['RoleName'],
                type: 'checkbox'
            })

:

                $(document.createElement("input")).attr({
                    type: 'checkbox',
                    id: 'cgr' + item['RoleId'],
                    name: 'cgroles',
                    value: item['RoleId'],
                    title: item['RoleName']
                })

everything works fine, and I get my long value as expected when i:

alert(document.forms[0].cgroles[8].value);

My question is why?

Test data:

var roles = {"ContactGroupRoles":[
    {"RoleId":1,"RoleName":"Pending"},
    {"RoleId":2,"RoleName":"CEO"},
    {"RoleId":3,"RoleName":"Financial Controller"},
    {"RoleId":4,"RoleName":"General Manager"},
    {"RoleId":5,"RoleName":"Production Manager"},
    {"RoleId":6,"RoleName":"Sales Manager"},
    {"RoleId":7,"RoleName":"Marketing Manager"},
    {"RoleId":8,"RoleName":"Sales Agent"},
    {"RoleId":9,"RoleName":"Customer Service"},
    {"RoleId":10,"RoleName":"Manager"}
  ]};
0
source share
1 answer

For some reason, IE (at least IE8) and Opera do not retain the attribute value(although Chrome / Firefox) by changing type. Here's a simplified test:

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

IE8/Opera:

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

Chrome/Firefox:

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

, Opera, , , ... , , type. , jQuery type , <input> , .

$("<input />", { value: 'Test', type: 'checkbox' }); , IMO .

+2

All Articles