Wednesday, March 17, 2010

How can I loop through the input elements of a particular div tag using JavaScript?

I need to retrieve the values of each input tag that is within a named div tag.

How can I loop through the input elements of a particular div tag using JavaScript?
Hello,





To loop through the input elements within an html page, you should use the getElementsByTagName method within the document DOM. That will return an array of elements with the supporting tagname.





A typical example would be the following:


=============================


// Grab all elements that have tagname input


var inputArr = document.getElementsByTagName( "input" );





// Loop through those elements and alert to user


for (var i = 0; i %26lt; inputArr.length; i++) alert( inputArr[i].value );


=============================





Notice we used Javascript DOM getElementsByTagName, you can read more about it from http://developer.mozilla.org/en/docs/DOM...





Since it is javascript, document is an object model, which is within a tree, you can change the initial location of that tree to a different subtree of your choice within the html page so you could do.





===============


var myDiv = document.getElementById( "myDiv" );


var inputArr = myDiv.getElementsByTagName( "input" );


for (var i = 0; i %26lt; inputArr.length; i++) alert( inputArr[i].value );


===============





Simple as that, it will check all input elements in the div who's id is "myDiv", you could use ID's or Class to distinguish which Div to focus.





The corresponding HTML page would be the following better formatted here http://mohamed.mansour.pastebin.com/f3d7...


==============


%26lt;html%26gt;


%26lt;head%26gt;


%26lt;script type="text/javascript"%26gt;





function handleTag()


{


// Grab all elements that have tagname input


var inputArr = document.getElementsByTagName("input");





// Loop through those elements and alert to user


for (var i = 0; i %26lt; inputArr.length; i++)


alert(inputArr[i].value);





}





%26lt;/script%26gt;


%26lt;/head%26gt;


%26lt;body%26gt;


%26lt;div id="myDiv"%26gt;


%26lt;input type="text" name="a" value="a" /%26gt;


%26lt;input type="text" name="a" value="b" /%26gt;


%26lt;input type="text" name="a" value="c" /%26gt;


%26lt;input type="text" name="a" value="d" /%26gt;


%26lt;input type="button" value="Find" onclick="handleTag()" /%26gt;


%26lt;/div%26gt;


%26lt;/body%26gt;


%26lt;/html%26gt;


==============





I hope this will help.





Good Luck



visual arts

No comments:

Post a Comment