简体   繁体   中英

How to get the value from multiple unique ids

I've been working on a form were i can make extra inputfields and selectfields thanks to this site! Al those fields get unique id (3011, 3012, 3013 to a max of 3019) and (rc1, rc2 etc.) with a removal link.

var i = 2;
var limit = 10;
function createInput () {
     if (i == limit) {
          alert("You have reached the limit of adding " + i + " inputs");
     }
     else

var field_area = document.getElementById('301X')
var div = document.createElement("div");
div.id = 'SA '+i;
var input = document.createElement("input");
div.innerHTML = '301'+i ;
input.id = '301'+i;
input.name = '3011';
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
input.value = "";
input.size = '80';
var rcnode = document.getElementById("rc1") // bepaal var van de select menu id relcode
var rcclone = rcnode.cloneNode(true); // bepaal var van de clone van de select
rcclone.id = 'rc'+i; // het nummeren van id clone
div.appendChild(input);
div.appendChild(rcclone);
field_area.appendChild(div);

and it works fine (would not surprise me that it can be beter) Now I want to catch the values. I succeed to cath it from one value with this script:

var x = 1;
function catchInput () {
var said = '301'+x; 
var rcid = 'rc'+x;
var Valsaid = document.getElementById(said).value;
var Valrcid = document.getElementById(rcid).value;
alert (said + ' ' + Valsaid + Valrcid);
}   

but I want to catch them all. I have been playing around with arrays and the for-loop but I can't figure it out. Any help, point in the right direction much appreciated.

Herman

There are several possibilities :

1) prefix your id's with a common string, then use jQuery (for example) to find all elements with id's starting with this prefix : $('[id^=yourPrefix]')

2) if you want to stick with POJS, "group" these dynamically generated elements by assigning a common class to them. you can then use getElementsByClassName() , which is not available in all browsers though (actually only a problem with IE <= 8)

3) still if you want to stick with POJS but need extended browser support, you can prefix your id's with a common string, then loop on your elements (maybe restricting the set using getElementsByTagName() ) and test if the id string starts with this prefix using indexOf() , for example (that's most probably how jQuery implements this functionality)

Hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM