开发者

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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜