Reputation: 123
I have this form
var sformElem = $('form[name="search_form"]')[0];
I am able to access the form element of name say 'fieldname' by
var inputField = sformElem.fieldname;
if (inputField) { // true
alert("this is true");
}
But when I am trying to acess the value using val() method of jquery, javascript crashes.
inputField.val() is not defined.
but doing inputField.value returns the value
Why didn't val() method work? Where am I making a mistake? Also, please suggest the most appropriate of accesing form elements by name.
One method I know of is
$("#form2 input[name=name]")
but here we get the form by id and input fields by name.
I want to get both form and form elements by name.
Upvotes: 1
Views: 175
Reputation: 1199
get it done by using
$('inputField id or class').attr('attribute');
the class or input field value can be called by the .attr()
method so that you can have that value in some variable.
Upvotes: 0
Reputation: 133453
Why didn't val() method work?
inputField.val()
returned "not defined" because inputField
is a DOM element and not a jQuery object. DOM elements don't have val()
method. So the error is correct.
You need to convert it into a jQuery object. like
$(inputField).val()
I want to get both form and form elements by name.
var elem = $('form[name="search_form"] input[name=name]');
Upvotes: 5
Reputation: 1776
var x = $("form[name = "search_form"]).get(0)
$("form[name = "search_form"]).get(0)
Since it is not a jquery object val will not work.Inorder to use val you have to make it a jquery object.
Like
$(x).val();
With this you will get the DOM Element
Upvotes: 0
Reputation: 1126
Do $(inputField).val()
as this passes the DOM Element through to jQuery therfore making val
available
Upvotes: 2