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

点点圈 提交于 2019-12-11 11:49:48

问题


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


来源:https://stackoverflow.com/questions/6235213/javascript-for-loop-to-change-the-name-of-textareas-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!