Gowtham
Gowtham

Reputation: 12180

Select all textboxes in a document using Javascript?

I would like to select all the contents of the text-boxes when a user clicks on it. But, since my document contains almost 5 text-boxes, instead of giving each text-box an ID selector or onfocus attribute, I would like to select all the text-boxes.

For example: var x = document.getElementsByTagName("p");

The above code selects all the paragraphs in a document. So, I need a similar code for all textboxes. I have tried replacing input and input[type=text] Nothing worked.

Upvotes: 1

Views: 6306

Answers (2)

Aditya Singh
Aditya Singh

Reputation: 9612

Try this out:-

http://jsfiddle.net/adiioo7/zvgHx/

JS:

var x = document.getElementsByTagName("INPUT");
var y = [];
var cnt2 = 0;
for (var cnt = 0; cnt < x.length; cnt++) {
    if (x[cnt].type == "text") y.push(x[cnt]);
}

alert("Total number of text inputs: " + y.length);

HTML:

<input type="text" id="input1" value="input1"></input>
<input type="text" id="input2" value="input2"></input>
<input type="text" id="input3" value="input3"></input>
<input type="text" id="input4" value="input4"></input>
<input type="text" id="input5" value="input5"></input>

So, array y will hold all inputs with type as text.

Upvotes: 5

ndrizza
ndrizza

Reputation: 3415

Use jQuery: $('input[type=text]') That will do the trick.

http://jquery.com/

Upvotes: -3

Related Questions