0

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");

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.