Jquery无法找到给定表单ID的表单输入

时间:2012-08-18 12:21:06

标签: javascript jquery forms

我正在尝试在我网站上的回复表单的sumbit上运行一个函数。 这些表单是在页面加载后由Javascript创建的,因此Jquery使用 live 函数来响应单击“.replyformsubmit”类按钮。

我需要脚本来记录表单的输入值,但似乎无法这样做。

目前找到了包含该按钮的表单的ID,但是使用它来尝试查找输入值似乎没有结果,这可能是学校男孩的错误,但我似乎无法理解它。

任何帮助都会很棒。

Jquery:

$(".replyformsubmit").live("click", function(){

var curform = $(this).closest('form').attr('id');//what form is the current one?


var comment = $('#' + curform + ' >  input[name=comment]"').val(); //comes out as undefined
var replyingSerial = $('#' + curform + ' >  input[name=replyingSerial]"').val(); //comes out as undefined

...

该脚本似乎无法找到 comment replyingSerial 的内容。

标准示例表单的HTML是:

<form action="com.php" method="post" id="replyform_quickreply_1345291318.6107" class="replyform">
<textarea name="comment" type="text" id="commenttextquickreply_1345291318.6107">
</textarea>
<br>
<input type="submit" value="send!" class="replyformsubmit">
<input type="hidden" style="visibilty: hidden;" name="replyingSerial" value="1345291318.6107"></form>

3 个答案:

答案 0 :(得分:2)

那是因为按钮是submit,它会阻止执行其余的代码。 请改用type='button'

或使用:

$('#formname').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});

答案 1 :(得分:2)

有几件事。注释是textarea,而不是输入,所以如果你想找到它,你需要使用textarea [name = comment]。

其次,您可以使用parent()并查找以使您的代码更清洁:

$(".replyformsubmit").on("click", function(){
   var parent = $(this).parent();
   var comment= parent.find("textarea[name=comment]");
    alert(comment.val());
});​

答案 2 :(得分:1)

将input type =“submit”更改为input type =“button”,因为它不允许其他代码在提交后执行,而不是.live()使用.on()

从jQuery 1.7开始,不推荐使用.live()方法。使用.on()附加事件处理程序。旧版jQuery的用户应该使用.delegate()而不是.live()。

此方法提供了将委托事件处理程序附加到页面的文档元素的方法,这可以在将内容动态添加到页面时简化事件处理程序的使用。有关详细信息,请参阅.on()方法中有关直接事件与委托事件的讨论。