Great javascript function
| From: | Anthony Martin | Date: | Thu, 28 Dec 2000 19:24:32 +0000 |
| Subject: | Great javascript function | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-32131@lists.php.net to get a copy of this message | ||
Ever use associative arrays to name a form element?
<INPUT type="submit" name="doThis[foo]" value="Do Foo">
Ever try to use that name with javascript?
alert ( document.myform.doThis['foo'].value ) ;
It doesn't work. Or at least, I don't see how it would. The brackets are
interpreted differently in javascript than in PHP. You would have to resort
to addressing javascript's element array, assuming you know what it is:
alert ( document.myform.elements[3].value ) ;
So, taking a technique from the ORACLE Form Builder suite, I wrote this
function in javascript:
function find_element ( form, element_name ) {
with ( form ) {
for ( var i = 0 ; i < elements.length ; i++ )
if ( elements[i].name == element_name )
return i ;
return -1 ;
}
}
And it's used like this:
var int = find_element ( document.myform, 'doThis[foo]' ) ;
if ( int > -1 )
alert ( document.myform.elements[int].value ) ;
else
alert ( 'No such element.' ) ;
You could do it all inline, too. You should check to see if it return -1,
meaning it couldn't find that value.
Enjoy!
Anthony