Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - get value from multiple inputs in an array

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

<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" id="webcampics">


  var elem = document.getElementById("webcampics");
  var names = [];
  for (var i = 0; i < elem.length; ++ i) {
     names += elem[i]+'|';
  }
  var webcamval = names;
like image 842
Hamada Badran Avatar asked Jan 14 '13 15:01

Hamada Badran


1 Answers

You shouldn't have elements with identical id's within the document. ID's have to be unique throughout your entire markup, by specification. If you do it anyways, methods like document.getElementById will only match the very first occurence for instance.

Use a class instead of ids.

<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">
<input type="hidden" value="'+image_url+'" name="webcampics[]" class="webcampics">

var inputs = document.getElementsByClassName( 'webcampics' ),
    names  = [].map.call(inputs, function( input ) {
        return input.value;
    }).join( '|' );

Demo: http://jsfiddle.net/QgJrq/

like image 177
jAndy Avatar answered Sep 28 '22 10:09

jAndy