title: Why does order of defining attributes for a dynamically created checkbox in jquery affect its value?
body: <p>I have this code in a js file:</p>
  
  <pre><code>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);
  }
  </code></pre>
  
  <p>I was wasting some time in other sections of code trying to work out why a call to </p>
  
  <pre><code>alert(document.forms[0].cgroles[8].value);
  </code></pre>
  
  <p>was returning a value of "on" when it should be returning a long. It turns out the problem is the order in which the attributes are defined. If i change this:</p>
  
  <pre><code>            $(document.createElement("input")).attr({
                  id: 'cgr' + item['RoleId'],
                  name: 'cgroles',
                  value: item['RoleId'],
                  title: item['RoleName'],
                  type: 'checkbox'
              })
  </code></pre>
  
  <p>to this:</p>
  
  <pre><code>                $(document.createElement("input")).attr({
                      type: 'checkbox',
                      id: 'cgr' + item['RoleId'],
                      name: 'cgroles',
                      value: item['RoleId'],
                      title: item['RoleName']
                  })
  </code></pre>
  
  <p>everything works fine and I get my long value as expected when i:</p>
  
  <pre><code>alert(document.forms[0].cgroles[8].value);
  </code></pre>
  
  <p>My question is why?</p>
  
  <p>Test Data:</p>
  
  <pre><code>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"}
    ]};
  </code></pre>