如果javascript中的条件为false,则避免在单击按钮时提交页面

如果javascript中的条件为false,则避免在单击按钮时提交页面,javascript,form-submit,Javascript,Form Submit,我正在检查javascript中的文本框值。并保存到数据库中。其中“作为我的保存”为“提交”类型。我想如果textbox值大于100,那么它应该发出警报。发出警报后,页面不应提交。我认为您正在寻找以下内容: <form id="myForm" onsubmit="return validateForm();"> <input type="text" id="textfield"/> <button type="submit">submit</button

我正在检查javascript中的文本框值。并保存到数据库中。其中“作为我的保存”为“提交”类型。我想如果textbox值大于100,那么它应该发出警报。发出警报后,页面不应提交。

我认为您正在寻找以下内容:

<form id="myForm" onsubmit="return validateForm();">
<input type="text" id="textfield"/>
<button type="submit">submit</button>
</form>
<script>
function validateForm(){
var value=parseInt(document.getElementById('textfield').value);
if(value>100){
alert('value is no good. larger then 100');
return false;
}
}
</script>

提交
函数validateForm(){
var value=parseInt(document.getElementById('textfield').value);
如果(值>100){
警报(“值不好,大于100”);
返回false;
}
}

如果您能向我展示您的代码,我很乐意帮助您实现这样一个功能。

这里有一个如何实现的示例。我使用了10个字符的限制来简化测试:

HTML:


首先,将该按钮的单击事件绑定到一个函数。其次,使用event.prevent default停止该按钮提交表单。第三,验证您想要的价值。如果已验证,请使用表单id提交表单。大概是这样的:

$("#ButtonId").on("click", function(event) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;

    if ($("#InputBoxID").val() < 100) {
        $("#FormId").submit();
    }
    else {
        alert("your message");
    }
});
$(“#按钮”)。在(“单击”上,函数(事件){
event.preventDefault?event.preventDefault():event.returnValue=false;
if($(“#InputBoxID”).val()<100){
$(“#FormId”).submit();
}
否则{
提醒(“您的信息”);
}
});

上面的代码在jQuery中,所以别忘了添加对jQuery的引用。

对不起,谷歌搜索“表单验证javascript”会得到大量结果。不管怎样,你试过什么?实际上我仍然面临着问题。若要在单击按钮事件时立即调用JavaScript函数时添加“return false”,请阻塞按钮。所以我只是想知道,虽然到目前为止还没有在谷歌上找到解决方案。
function checkValue(textbox) {
    if (textbox.value.length > 10) {
        alert("TEXT TOO LONG");
        document.getElementById("sendButton").disabled = true;
    }
    else
        document.getElementById("sendButton").disabled = false;        
}
$("#ButtonId").on("click", function(event) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;

    if ($("#InputBoxID").val() < 100) {
        $("#FormId").submit();
    }
    else {
        alert("your message");
    }
});