adam78 adam78 - 1 year ago 216
Javascript Question

jQuery get value from form object?

I have the following form:

<input type="radio" name="foo" value="1" checked="checked" />
<input type="radio" name="foo" value="0" />
<input name="this" value="xxx" />
<select name="bar">
<option value="hi" selected="selected">Hi</option>
<option value="ho">Ho</option>
<a class="js-add" href="#" >Add</a>

I have the following function which passes the entire form when the add link is clicked:

$(".js-add").click(function (e) {

values = getFormValues($("form"));

getFormValues = function($form) {
var bar = $;


How do I retrieve a particular input value from the form object. So for example in the above
function I want to grab the value of the bar input field but the above doesn't work. Normally I'd just do this:
But how do I get the same from the form object?

Answer Source

What you're passing into your function isn't a form object, it's a jQuery object which is wrapped around an HTMLFormElement object. jQuery's API lets you easily find elements within that element via find (one of the tree traversal methods):1


Then you need to return that value from your function, so:

return $form.find("[name=bar]").val();

If the name isn't a valid CSS identifier (it is in your example, but...), use quotes around it:

return $form.find("[name='bar']").val();

1 It's pretty easy with the native DOM as well, but you're using jQuery, so...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download