简体   繁体   中英

Javascript for loop to change the name of textareas in a function

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?

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;
    // ...
}

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.
}

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

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';
    }

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;
    }
} 

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