Can I use JavaScript to set the 'name' attribute?

前端 未结 7 582
时光取名叫无心
时光取名叫无心 2020-12-11 16:56

According to SitePoint (and my own experiments), the IE implementation of \"setAttribute()\" is buggy and unreliable.

Also according to SitePoint, the name

相关标签:
7条回答
  • 2020-12-11 17:03

    The name property is not read only for input elements.

    See the spec.

    0 讨论(0)
  • 2020-12-11 17:03

    IE DOM does not allow me to change name attribute on runtime. However, using jQuery to update the name attribute works on IE. I tested on IE9. For examples,

    <input id="ID0E2B" name="Field2" value="3" type="radio" />
    $("#ID0E2B").attr("name", newName);
    
    0 讨论(0)
  • 2020-12-11 17:04

    Sitepoint liesis talking about a different usage of ‘name’ (see Anthony's comment). It's not read-only, it's just there's a long-standing IE bug (up to v7) where setting ‘name’ on form fields is only partially effective. Radio buttons in particular don't accept it properly.

    The Microsoft-endorsed solution, as detailed here is to use a horrific misfeature of IE's version of the createElement call to set attributes at the same time:

    var radio= document.createElement('<input type="radio" name="test" value="a" />');
    

    Probably a better way would simply be to use good old innerHTML, eg.:

    var div= document.createElement('div');
    div.innerHTML= '<input type="radio" name="test" value="a" />';
    var radio= div.firstChild;
    
    0 讨论(0)
  • 2020-12-11 17:10

    Have you tried simply assigning a new name to the elements name property? I'm not sure how cross-browser that is but it shold work with anything supporting DOM level 1.

    I'm not sure why you would use setAttribute to perform this?

    0 讨论(0)
  • 2020-12-11 17:16

    Looking at W3C DOM Compatibility - Core you could try using setAttributeNode() instead of setAttribute(). It may work on IE 6 and above.

    0 讨论(0)
  • 2020-12-11 17:23

    Why not use setAttribute("name", yourValue) it works perfectly fine.

    0 讨论(0)
提交回复
热议问题