Forum Moderators: open

Message Too Old, No Replies

how to use getElementByID in context of form

context senstive getElementByID

         

Demaestro

7:29 pm on Jul 12, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hey all,

I am sure there is a simple way to do this but I am not putting my brain on it.

I have a page that has more than 1 form, the forms can be distinguished by ID, but the elements that live in them can't.

I know it is incorrect to have an id used more than once..... but is it possible for this to work as is or do I need to revisit the way it is laid out?

<form id="form1" onSubmit="return validate_form();>
<input type="text" value="" name="the_quantity" id="the_quantity">
<input type="submit">
</form>

<form id="form2" onSubmit="return validate_form();>
<input type="text" value="" name="the_quantity" id="the_quantity">
<input type="submit" >
</form>

<script type="text/javascript">
function validate_form {
alert(document.getElementById('the_quantity').value);
}
</script>

How would I teach this function to know which "the_quantity" to be looking at? IE the one contained in the form that was submitted?

Fotiman

8:32 pm on Jul 12, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Yeah, having more than one element with the same ID is problematic. Here's what I would do.

1. Remove the id attribute from those elements (or make then unique per form)
2. Access the named element via the form:
a. Change your onsubmit handlers to: onsubmit="return validate_form(this);"
b. Change your validate_form function to be:

function validate_form(frm) {
alert(frm['the_quantity'].value);
}


Named inputs can be accessed directly as members of the form object, so pass in the form (ie - this) to your function, then find the named items as members of that element.

Demaestro

8:36 pm on Jul 12, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Fotiman,

Thanks so much, that is exactly what I needed.