Hamada Badran
Hamada Badran

Reputation: 129

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;

Upvotes: 5

Views: 82169

Answers (3)

Yusaf Khaliq
Yusaf Khaliq

Reputation: 3393

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/

Upvotes: 3

jAndy
jAndy

Reputation: 236092

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/

Upvotes: 8

Evan Davis
Evan Davis

Reputation: 36592

  1. You shouldn't have more than one element with the same id.

  2. getElementById returns exactly one element; use getElementsByName which will return the list you seek.

Upvotes: 2

Related Questions