我有一个带有 onchange 事件的文本框。当该函数触发时,会显示一个隐藏元素。但是,当由于单击提交按钮而触发 onchange 时,该元素会非常短暂地显示,因为提交函数会在之后立即触发。如果是导致文本框“失去焦点”的元素,是否有任何方法可以防止提交按钮不触发?
编辑:
jquery 1.3.2
<script type="text/javascript">
function phoneChanged(currentElement, valueToCompareAgainst) {
$('#divPhoneChanged').show('slow');
}
</script>
<div id="divChange">
<asp:TextBox ID="txtPhoneCell" runat="server"></asp:TextBox>
</div>
<div id="divPhoneChanged" style="display: none; padding-bottom: 15px">
<asp:Label ID="lblPhoneChanged" runat="server" Font-Bold="true" Text="Your phone number on file will be updated with the value you provided above.">
</asp:Label>
</div>
<div style="margin-top: 10px">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</div>
并在页面加载的隐藏代码中:
txtPhoneCell.Attributes.Add("onchange", String.Format("phoneChanged(this, '{0}')", strPhoneCell))
最佳答案
我使用标准 html 代码编写了代码。所以没有asp.net。它依赖于在触发 onchange
事件时将全局值 (startSubmit
) 设置为 false
。仅当其值为 true 时,表单才会提交。
替代方案:
- 您可以定义一个隐藏输入,而不是使用
startSubmit
变量,当触发onchange
事件时,该输入的值会更改为false
。 - 您可以在
form
元素上定义onsubmit
属性,而不是使用.submit()
jquery 方法。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo - Prevent submit</title>
<script src="https://code.jquery.com/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var startSubmit = true;
$(document).ready(function () {
$('#theForm').submit(function (event) {
if (!startSubmit) {
event.preventDefault();
startSubmit = true; // Set to "true", so that the next click submits the form.
return false;
}
return true;
});
});
function phoneChanged(currentElement, valueToCompareAgainst) {
$('#divPhoneChanged').show('slow');
startSubmit = false;
}
</script>
</head>
<body>
<!-- This random number changes on each page refresh, e.g. on each form submission. -->
Page reloaded: <strong><?php echo rand(1, 99999); ?></strong>
<br/><br/>
<form id="theForm" action="" method="post">
<div id="divChange">
<input type="text" id="txtPhoneCell" onchange="phoneChanged(this, '4');">
</div>
<div id="divPhoneChanged" style="display: none; padding-bottom: 15px">
<label id="lblPhoneChanged">
Your phone number on file will be updated with the value you provided above.
</label>
</div>
<div style="margin-top: 10px">
<button type="submit" id="btnSubmit">
Submit
</button>
</div>
</form>
</body>
</html>
<小时/>
编辑:
我做了很多测试,但找不到比上面的解决方案更优雅的解决方案。就我个人而言,我会选择像 @rickjerrity 推荐的那样这样做:
<script type="text/javascript">
function phoneChanged(currentElement, valueToCompareAgainst) {
$('#divPhoneChanged').show('slow');
}
</script>
[...]
<input type="text" id="txtPhoneCell" onkeyup="phoneChanged(this, '4');">
关于javascript - 如何防止文本框失去焦点后提交按钮提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51051690/