Javascript for loop to change the name of textarea

2019-08-15 05:18发布

问题:

I have created 50 textareas with names def1,def2,def3.....,def50. In my body onLoad() function,I want the same value is set in all these textboxes.

Instead of writing the code 50 times, How can I write some Javascript code to set the value of the textarea, ie in a loop?

回答1:

I suggest to read the MDC JavaScript guide, as loops and string concatenation are fairly basic operations:

for(var i = 1; i < 51; i++) {
    var nameOfTextarea = 'def' + i;
    // ...
}


回答2:

I would give your textboxes ID's (not just names) if possible, and then do something like the following:

var namePrefix = "def";
for(var i = 1; i <= 50; ++i)
{
    var textbox = getElementById(namePrefix + i);
    // do something to textbox number i.
}


回答3:

Try jquery for this:

<input type="text" id="t1"/>
<input type="text" id="t2"/>
<input type="text" id="t3"/>

The Jquery code:

var arr = [ "t1", "t2", "t3" ];
jQuery.each(arr, function() {
      $("#"+this).val("hello");//$("#" + this).text("hello");
   });

Here is the working demo



回答4:

Try this.

var textareas = document.getElementsByTagName("textarea");
for(var i=0;i<textareas.length;i++){
    if(textareas[i].id.indexOf("def") == 0){
        textareas[i].value = textareas[i].id;
    }
} 


回答5:

You can use tagname property but it will not work if you have some more textbox anywhere else in your page

 function loader(){
    for(var i=0;i<50;i++)
    document.getElementsByName("def"+i)[0].value='Any Value';
    }