我正在尝试创建一个提交表单,该表单在单击div后显示,然后检索填写的表单数据。以下是我正在玩一天的测试。变量“term”始终打印为undefined。有人可以帮帮我吗?
$(document).ready(function () {
$("#nexttable").on("click", "#addcomment", function () {
document.getElementById("nexttable").innerHTML = "<form action='maindatabase.php' id='commentform' method='post'><textarea name='newcomment' placeholder='Start typing your comment... (required)' rows='5' cols='50' required></textarea><br />"
+ "<span id='sbutton'><input type='button' value='Submit'></span><input type='hidden' name='inputtype' value='3'></form>";
});
});
$(document).ready(function () {
$("#nexttable").on("click", "#sbutton", function () {
var $form = $(this);
var term = $form.find("input[name='newcomment']").val();
document.getElementById("nexttable").innerHTML = term;
});
});
答案 0 :(得分:2)
页面上没有名称为newcomment的输入,其为textarea,即
$form.find( "input[name='newcomment']" ).val();
找不到任何东西,应该是
$form.find( "textarea[name='newcomment']" ).val();
事件处理程序中的this
也存在问题,因为它是委派的事件处理程序
$(document).ready(function () {
$("#nexttable").on("click", "#sbutton", function () {
var $form = $(this); // <-- HERE, the this I do believe is in reference to the #sbutton element, not anyting to do with a form
var term = $form.find("input[name='newcomment']").val();
document.getElementById("nexttable").innerHTML = term;
});
});
我会把它改成更像
的东西 $(document).ready(function () {
$("#nexttable").on("click", "#sbutton", function () {
var $form = $(this).parents('form'); // <-- HERE, actually get the form element, which will be a prent of this element clicked ont
var term = $form.find("input[name='newcomment']").val();
document.getElementById("nexttable").innerHTML = term;
});
});