简体   繁体   中英

Getting a dynamic textbox name using javascript

Please forgiving if the title is a little non-descriptive. Here is what im doing. Im making dynamic textboxes in a table using javascript. For example i add one row to the table, give the textbox a name for instance tname, i want to make each textbox unique so i add a row number to the end of it, so the textbox name is tname1, next would be tname2...etc. Now I want to create another function to loop through this table to get all of the values. Here is the code im using to get the value of the textbox below. I didnt put the for loop b/c I know that the loop works, b/ci got the correct number of rows.

txt = document.getElementById('tname' + a)
alert(txt.value) 

I know that there is a function that you put around this: ('tname' + a) to let javascript know that your concatenating it together b/ci did it before just cant remember the function. If any can help, it would be very much appreciated

You need to use ID and name. For example,

<input type="text" name="tname1" />

should be

<input type="text" name="tname1" id="tname1"/>

If you assigned the id (not name) then dirty pure JavaScript work around is:

var a = 1;
while (true) {
    var id = 'tname' + a;
    var txt = document.getElementById(id);
    if (txt == null)
        break;
    alert("value of " + id + " is: " + txt.value);
    a++;
}

This will keep looking for elements, until it can't find any - hope this makes sense.

Use JQuery . It simplifies tasks like this:

$('input[type="text"]').map(function(){
    return (this.value.length > 0) ? this.value : null;
}).get().join(',');

Working demo: http://jsfiddle.net/AlienWebguy/wLteQ/

Have you tried:

var els = document.getElementsByName(...);
// Or if you only focusing on newer browsers:
var els = document.querySelectorAll(..);

// els is now a HTMLCollection / NodeList
console.log(els[0].value);

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