JavaScript - get value from multiple inputs in an array

后端 未结 3 486
抹茶落季
抹茶落季 2020-12-30 16:08

I am trying to get the value from muliple inputs with the same id in an array. I already used the forum, but haven\'t find a solution for me.

Exmaple



        
3条回答
  •  爱一瞬间的悲伤
    2020-12-30 16:58

    What you are asking for is wrong very wrong, it is recommended IDs should be unqiue, but for learners sake here's what you would do

      var elem = document.getElementsByTagName("input");
      var names = [];
      for (var i = 0; i < elem.length; ++i) {
        if (typeof elem[i].attributes.id !== "undefined") {
          if (elem[i].attributes.id.value == "webcampics") {
            names.push(elem[i].value);
          }
        }
      }
      var webcamval = names;
    

    http://jsfiddle.net/5vamG/

    Due to someone down voting after giving a full explanation why the above mentioned method is wrong, however does exactly what youve asked for, here's the correct method.

    change all the inputs id to class

      var elem = document.getElementsByClassName("webcampics");
      var names = [];
      for (var i = 0; i < elem.length; ++i) {
        if (typeof elem[i].value !== "undefined") {
            names.push(elem[i].value);
          }
        }
      }
      var webcamval = names;
    

    http://jsfiddle.net/5vamG/1/

提交回复
热议问题