PDA

View Full Version : getElementById and accessing form data


delinear
05-04-2005, 11:32 AM
I have to put together some calculators for an accountancy project but I'm having a problem passing a form name to a function and then using that to access the values of the form's elements. Here's how I'm trying to do this, it works in IE but not in FireFox, anyone know why or how I can do this?

<script language="javascript">

function alertme(lv) {
alert(document.getElementById(lv).field_loan.value);
}

</script>

<form name="calc_loan" method="post" action="">
<input name="field_loan" type="text" id="field_loan" value="">
<input type="submit" name="Submit" value="Submit" onClick="alertme(this.form.name); return false;">
</form>

delinear
05-04-2005, 12:07 PM
*sigh*

Okay, ignore that... I really should have remembered that it you're going to use getElementById it's useful to actually give the element an id to start with :rolleyes:

Kor
05-04-2005, 01:18 PM
You can still use the old way of accesing form's elements as
document.forms['name_or_index'].elements['name_or_order']

You can also use a DOM reference by name, as well, except that you must specify the index order, as name can be (in radio buttons' case) multiple

document.getElementsByName('element_name')[0]

delinear
05-04-2005, 01:49 PM
Ah, I didn't know there was a getElementsByName, thanks :D

glenngv
05-05-2005, 12:53 PM
You can simply pass this.form and never bother with the form name or id.

<input type="submit" name="Submit" value="Submit" onClick="alertme(this.form); return false;">
...
function alertme(oFrm) {
alert(oFrm.field_loan.value);
}