View Full Version : Trying to access all the inputs within a span

09-08-2006, 04:38 PM
I have a basic setup where I call on a function that shows/hides a span. The problem that I run into is I need to manipulate the values of the inputs within the span so that if they are hidden, my validator does not attempt to reject them upon validation onSubmit. And then if they are shown, I want to clear the values out so that the user can input data.

My question is:
is there some way to cycle through, or get an array of all of the elements from within a span - when you have the span id as an argument in a function:

ex) function changeSpan(spanname) { function body; }

Help is appreciated.

09-08-2006, 04:56 PM
You can use a for loop in conjunction with getElementsByTagName().

<script type="text/javascript">
function setInput()
var spans = document.getElementsByTagName('span');
for(var i = 0; i < spans.length; i++)
if(spans[i].firstChild.nodeName.toUpperCase() == 'INPUT')
window.onload = setInput;
<form action="#" method="post">
<span><input type="text" value="test"></span>
<span><input type="text" value="blah2"></span>

09-08-2006, 06:08 PM
Thank you, that looks like what I was looking for. Now I have a question about that line of code (don't hate me too much, I'm picking up a book on DOM this afternoon) - what exactly is this line for?

if(spans[i].firstChild.nodeName.toUpperCase() == ' INPUT')

I'm not very familiar with the whole Child/Parent thing yet, because I haven't had to work too much with them. Are you just filtering out the Input fields from the other things contained in the span?

Just trying to understand here, do you change everything toUpperCase() just in case there are mixed capitalizations of the word input in my input tags?

09-08-2006, 08:02 PM
Every HTML element on a page has a nodeName which usually tells what type of element it is. That line there is checking to see if the first element in the span is an input element. If it is then do this, if not keep going to the next span until that statement is true. Yes I change the nodeName to uppercase because some browsers may put it as lowercase in which the line will fail. You could just as well do toLowerCase but by default Firefox uses uppercase so I use uppercase as well. If you have more elements inside of the span then the test will fail. If thats the case then you'll have to use a for loop to go through childNodes checking their nodeName.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum