【发布时间】:2016-01-29 03:10:28
【问题描述】:
我用一个按钮打开我的对话框,然后我将光标放在一个输入字段中,然后按 Enter 我的对话框关闭,此行被插入到地址栏:
jQuery:
$('#dialog').load("form-incident.php").dialog({
title: "Add Incident",
autoOpen: false,
resizable: false,
width: 800,
modal:true,
position: ['center', 'top+50'],
buttons: {
Add: function(){
$.ajax({
url : 'save.php',
type : 'POST',
data : $('form').serialize(),
context: $(this),
success: function (result) {
if (result === "true") {
alert('Incident has been added successfully');
} else {
alert('ERROR: Cannot insert data to MySQL table');
}
window.location.reload();
$(this).dialog( "close" );
},
error : function(){
alert('ERROR: Check database connection');
}
});
},
Cancel: function() {
$(this).dialog( "close" );
}
}
});
form-incident.php:
<form>
Name: <input type="text" name="name" id="name"><br><br>
Project:
<select name="project" id="project">
<option value="test">Test</option>
</select><br><br>
Incident:<br> <textarea name="incident" id="incident" style="resize:none; width: 100%;" rows="14" cols="94"></textarea>
</form>
如果之前填写的表格有一些建议,我该如何解决这个问题,使对话框不会关闭但仍会响应输入?
【问题讨论】:
-
没有看到 form-incident.php 返回的渲染标记,我不能肯定地说。但是,我猜这包括一个表单(使用
get的方法,因为您看到查询字符串值添加到您的 URL)。如果输入具有焦点并且用户按下回车,所有浏览器都会自动提交表单。如果表单被设置为提交给自己,当它被提交时,它会重新加载页面。您可以处理提交事件并在其上调用 preventDefault() 。但是我不确定您所说的“但如果之前填写表格的地方有一些建议,仍然会做出反应”。 -
@Elezar 感谢您的回复,如果我在提交事件对话框上调用 preventDefault() 仍然关闭并且查询字符串被插入到地址栏。我也尝试设置一个 keyCode 事件,但是如果我应该填写我的输入字段时有任何建议,我就不能使用 enter。
-
好的,这里还有其他事情。您在该表单内没有提交按钮,因此按 Enter 甚至不应该提交它。不过,它看起来仍然像表单提交,因为我认为 Enter 会导致导航的唯一其他方式是通过显式代码。页面上的某个地方是否可能还有另一个表单元素,整个对话框都在其中?
-
在我的 jQuery 代码中,我有一个名为 add 的函数,当我按下添加按钮时,它会使用 Ajax 提交我的表单。但是,当我在输入字段中按 Enter 键时,它仍然会关闭我的对话框。不,我的页面上没有任何其他表单元素。
标签: javascript jquery jquery-ui-dialog