Skip to content Skip to sidebar Skip to footer

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 t

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

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

Solution 3:

Try jquery for this:

<inputtype="text"id="t1"/>
<inputtype="text"id="t2"/>
<inputtype="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

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

Post a Comment for "Javascript For Loop To Change The Name Of Textareas In A Function"