从特定表单获取特定输入?

时间:2011-10-02 17:32:44

标签: javascript jquery

我很难从特定表单中获取特定输入。有什么提示吗?

<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>

如果提交了frm_addtag-1,我只想从该表单中获取标记输入而不是其他表单。

当我执行类似下面的操作时,无论提交哪种表单,它都会从任何其他表单返回标记输入。

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

2 个答案:

答案 0 :(得分:2)

ID应该是唯一的。

更改ID后,使用.val()获取元素的值。

此外,当您提交表单时,将表单中的元素添加到请求中。

答案 1 :(得分:1)

您不能在同一页面上拥有多个具有相同ID的元素。为什么不这样做:

<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>

这是为了获得价值:

$('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
});
相关问题