Reputation: 2191
I have multiple forms on one page where the form DOM object is being passed as an arugument to a JavaScript function like:
<form name="form1" method="post" action="">
<input id="textfield1" type="text" name="textfield1">
<input id="textfield2" type="text" name="textfield2">
<input id="textfield3" type="text" name="textfield3">
<input name="button" type="button" id="btn" value="Get Info" onClick="getdata(this.form)">
</form><form name="form2" method="post" action="">
<input id="textfield1" type="text" name="textfield1">
<input id="textfield2" type="text" name="textfield2">
<input id="textfield3" type="text" name="textfield3">
<input name="button" type="button" id="btn" value="Get Info" onClick="getdata(this.form)">
</form>
<form name="form3" method="post" action="">
<input id="textfield1" type="text" name="textfield1">
<input id="textfield2" type="text" name="textfield2">
<input id="textfield3" type="text" name="textfield3">
<input name="button" type="button" id="btn" value="Get Info" onClick="getdata(this.form)">
</form>
function getdata(form){
alert("the value is: " + form.getElementById('textfield1).value);
}
How would I access the DOM object, passed in getdata(form), with jQuery?
I've tired $(form) but that only seems to access the button object, not other inputs in the form.
Thanks for any help.
Upvotes: 0
Views: 199
Reputation: 595
You can try in getData function like this-
form.fieldName.value
Upvotes: 0
Reputation: 1864
This returns the DOM elements for form1
$('form[name=form1]').get()
or for all the forms
$('form').get()
To access individual form elements you can access for example button
$('form[name=form1] #btn')
Upvotes: 0
Reputation: 129802
$(form)
should indeed give you a jQuery reference to the form, whereas simply form
will be the DOM node itself. Demo
For what you're trying to acheive, though, you might be better off passing a DOM node as context to your selector:
$('#li_address', form).val()
However, since you're getting an element by ID, you won't need context – because you only have one, right? But a reasonable demo of using the DOM node as context is here.
Since you're working with jQuery, though, you might want to switch from onClick
and handle the event binding in jQuery as well. Note that I'm accessing all buttons with .btn
assuming class="btn"
rather than id="btn"
. Again, ID should be unique in the entire document. Do not deviate from this. It'll bite you.
$('form .btn').click(function() {
// this = button DOM node
var form = $(this).closest('form');
form.submit(); // or whatever
});
Upvotes: 1