我使用jQuery将表单从侧边栏加载到主页面。现在我想使用jQuery提交这个表单,但是我很难做到这一点。我使用相同的jQuery代码来提交未加载jQuery的表单。希望有人能看出我做错了什么。
如何修改以下代码以便提交表单?
加载表单的链接:
<a href="#" id="link1">Exam1</a>
请加载表格:
$(document).ready(function(){
$('#link1').click(function(){
$('#show').load('exam.php');
});
});
FORM:
<form action="form.php" id="exam" method="post" >
<input type="text" name="new_exam"/>
<button id="sub" name="" style="color:#e75618; padding:5px 66px" class="btn btn-default" ><b>Add Exam</b></button>
</form>
提交表格:
$("#sub").click( function() {
$.post( $("#exam").attr("action"), $("#exam").serialize(), function(info){ $("#result").html(info); } );
clearInput();
$("html, body").animate({ scrollTop: 0 }, "slow");
});
$("#exam").submit( function() {
return false;
});
function clearInput() {
$("#exam")[0].reset();
PHP:
$new_exam = $_POST['new_exam'];
$insert_exam = "insert into examination (exam_title) values ('$new_exam')";
$run_exam = mysqli_query($con, $insert_exam);
if($run_exam){
echo "New Exam inserted";
}
答案 0 :(得分:1)
要在动态创建的元素上绑定事件,您必须将事件绑定在元素的父元素上:
$('body').on('click', '#sub', function(){
$.post($("#exam").attr("action"), $("#exam").serialize(), function(info){ $("#result").html(info); } );
clearInput();
$("html, body").animate({ scrollTop: 0 }, "slow");
});
$('body').on('submit', '#exam', function(event){
event.preventDefault();
return false;
});