Я подготовил код, используя стандартный HTML-код. Так что нет asp.net. Он полагается на установку глобального значения (startSubmit
) на false
, когда срабатывает событие onchange
. Форма отправляется, только если ее значение равно true.
Альтернативы:
- Вместо переменной
startSubmit
вы можете задать скрытый ввод, значение которого изменяется на false
при запуске события onchange
.
- Вместо использования
.submit()
метода jquery вы можете определить атрибут onsubmit
для элемента form
.
<Ч />
<!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');">