Setting name of DOM-created element fails in IE — workaround?

后端 未结 2 1863
既然无缘
既然无缘 2020-12-19 21:33

I got bit hard by this today:

function mk_input( name, val ) {
    var inp = document.createElement( \'input\' );
    inp.name = name;
    inp.value = val;
          


        
2条回答
  •  没有蜡笔的小新
    2020-12-19 22:00

    Just to re-iterate the problem: in IE, programatically setting the name attribute on an element created via document.createElement('input') is not reflected in getElementsByName, form.elements (if appending to a form), and is not submitted with the form (again, if appending to a form) [Reference].

    Here's the workaround I've used in the past (adapted to your question from here):

    function mk_input( name, val ) {
        var inp;
        try {
            inp = document.createElement('');
        } catch(e) {
            inp = document.createElement("input");
            inp.type = "hidden";
            inp.name = name;
        }
        inp.value = val;
        return inp
    }
    

    This is akin to feature detection (as opposed to browser detection). The first createElement will succeed in IE, while the latter will succeed in standards-compliant browsers.

    And of course the jQuery equivalent since you tagged the question as such:

    function mk_input( name, val ) {
        return $('')
            .val(val)
            .get(0)
    }
    

    (as a sidenote, under the hood jQuery is doing what you describe in your question: it creates a dummy

    and sets its innerHTML to the
提交回复
热议问题