Mike
Mike

Reputation: 980

Getting a specific input from a specific form?

I'm having difficulty grabbing a specific input from a specific form. Any tips?

<form id ="frm_addtag-1">
    <input type="text" name="tag" id="tag">
</form>

<form id ="frm_addtag-2">
    <input type="text" name="tag" id="tag">
</form>

<form id ="frm_addtag-3">
    <input type="text" name="tag" id="tag">
</form>

If frm_addtag-1 is submitted, I only want to grab the tag input from that form and not the other forms.

When I do something like the below, it will return the tag inputs from any other the forms regardless of which form is submitted.

var tag = $("#tag");
var tag = tag.attr("value");

Upvotes: 0

Views: 1416

Answers (2)

vzwick
vzwick

Reputation: 11044

You cannot have multiple elements with the same ID on the same page. Why not do something like this:

<form id ="frm_addtag-1">
    <input type="text" name="tag1" id="tag1">
</form>

<form id ="frm_addtag-2">
    <input type="text" name="tag2" id="tag2">
</form>

<form id ="frm_addtag-3">
    <input type="text" name="tag3" id="tag3">
</form>

And this to get the value:

$('form').bind('submit', function(e){ // when any form on the page is submitted
    e.preventDefault(); // prevent the actual submit so the browser won't leave the current page
    var tag = $('input[name^="tag"]', this).val(); // the value of an input element whose name attribute starts with "tag" and that is a child of the current form
});

Upvotes: 1

Rob W
Rob W

Reputation: 349012

IDs should be unique.

After changing the IDs, use .val() to get the value of an element.

Besides, when you submit a form, only the elements WITHIN that form are added to the request.

Upvotes: 2

Related Questions