0

Let's say I have a number of select fields. The quantity of those select fields is not fixed. They will be genereated by the user. BUT they will have an incremented ID like this:

<select id="select1"></select>
<select id="select2"></select>
<select id="select3"></select>

What I need is for a JavaSript to pull the values from those selects based on their ID, assuming I have the CURRENT count of the selects in another variable.

So I'm looking for somehting to make this work like:

for (var i =1; i<currentcount; i++){
var resultvar = select(//now I have to add the var i in here but don't know how).value;
alert(resultvar);
}
Mike Pala
  • 766
  • 1
  • 11
  • 39
  • 1
    document.getElementById('select' + i).value – Danmoreng Jul 07 '17 at 09:45
  • 2
    you don't even need to keep the count in another variable necessarily. If you give all the selects the same class, you can easily use script to pull out all the elements with that class at any given moment, and loop through them to get the values. – ADyson Jul 07 '17 at 09:45
  • 1
    you can get all select by this `$('select.yourclassname').each(function() {`. – urfusion Jul 07 '17 at 09:46
  • @urfusion is there jQuery in this code anywhere? No. – Danmoreng Jul 07 '17 at 09:46
  • @Danmoreng : Yes, I know, Thanks for pointing this out. I am trying to providing an alternate way. Is there any issue with that? – urfusion Jul 07 '17 at 09:48
  • @urfusion you should at least say that this command is using a library and not vanilla js... – Danmoreng Jul 07 '17 at 09:48
  • @Danmoreng : has he mention something like `vanilla js` ? Ohh, Sorry – urfusion Jul 07 '17 at 09:49
  • 1
    @urfusion If the question has no jQuery tag and the code shows no sign of the usuage of the library, you can assume he is not using it. Therfor if you suggest an answer which is using a library, you should at least say that it's from a library. – Danmoreng Jul 07 '17 at 09:54
  • @Quentin I'm really not sure that duplicate is directly related to this. This question is asking how to loop through a dynamically generated list of elements. The duplicate you've marked is to to with accessing object properties using a string to represent the property. Here the OP could either generate the ID selector strings dynamically (I guess this is what you had in mind, but selectors are not object properties), or a better solution would be to use a class. Not really the same thing as accessing object properties. – ADyson Jul 07 '17 at 10:06

0 Answers0