我有一个简单的表单布局,要求用户输入代码。现在该代码将确定要执行的 php 脚本,但这不是我的问题。您会看到,当用户输入错误内容时,该页面会执行它应该执行的操作,并向用户显示一条错误消息,内容为……错误代码 yadadada。但是当用户返回输入正确的代码时,它仍然会给出错误。除非用户刷新页面并在第一次尝试时输入正确的代码,然后才会允许他们通过。
我必须拥有那个
event.preventDefault();
因为否则如果用户输入了错误的代码,它会自动刷新页面并且不会让用户知道代码是错误的。我怎样才能克服这个问题?我尝试将 html 字段设置为空白,但这似乎没有帮助
<form id="formRSVP" method="post" style="text-align: center;">
<div class="form-group">
<label for="rsvpCode"><span id="rsvpTitle">RSVP Code: </span></label>
<br />
<span id="formErrorMsg" style="color:red;"></span>
<input id= "rsvpCodeInput" type="code" class="form-control" name="rsvpCodeInput" placeholder="Enter RSVP Code here..">
</div>
<div id="rsvpFormSubmit">
<button type="submit" class="btn btn-default">Submit</button>
</div>
<script>
$("#rsvpFormSubmit").click(function(){
var userInput = $('#rsvpCodeInput').val().toLowerCase();
$('#formRSVP').submit(function(event){
if(userInput === 'emoya' || userInput === 'rehersal'){
if(userInput === 'emoya'){
$('#formRSVP').attr("action","rsvp_wedding.php");
}
else if(userInput === 'rehersal'){
$('#formRSVP').attr("action","rsvp_rehersal.php");
}
else{
alert("This shouldn't be displaying, if it is, please email: duan_uys@icloud.com.");
}
return;
}
else{
event.preventDefault();
$('#formErrorMsg').text('Confirmation Code Invalid. Please try again.').show();
alert('For testing purposes, type in either: emoya or rehersal');
$("#rsvpCodeInput").val('');
}
});
});
</script>
</form>
最佳答案
这里的问题很可能是因为 userInput
在第一次输入后从未改变。
我敢打赌您按回车键提交它,这会绕过您的变量分配。尝试从 .submit()
外部删除 .click()
并将 var userInput = $('#rsvpCodeInput').val() .toLowerCase();
就在 .submit()
的内部。
.click()
已经是与 .submit()
一起发生的已知事件(实际上反之亦然)。单击按钮时,使用它会触发额外的 .submit()
。
关于javascript - 表单提交后,它不会清除或重置 html 元素。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27748131/