Javascript 更新表单值并停止提交
我有一个HTML代码:Javascript 更新表单值并停止提交,javascript,forms,Javascript,Forms,我有一个HTML代码: <form action="?" id="form1" method="POST" onsubmit="return g.submitForm();"> <input type="text" name="posX" id="formPosX" /> <input type="text" name="posY" id="formPosY" /> <input type="submit" value="Send
<form action="?" id="form1" method="POST" onsubmit="return g.submitForm();">
<input type="text" name="posX" id="formPosX" />
<input type="text" name="posY" id="formPosY" />
<input type="submit" value="Send" />
</form>
并且此表单总是在更新值后发送。我的目标是更新错误的值并停止提交表单(我希望通过AJAX来完成)。当我删除IF语句时,代码工作正常,但我需要更新一些值(如果是,还显示一个错误)
希望您能理解我糟糕的英语:)您假设表单输入中的值是整数,而实际上它将被视为字符串数据类型。在应用比较之前,请尝试将值转换为数字
if ( parseInt(form.posX.value) > 100 )
{
form.posX.value = "100";
}
我已经修改了您的代码,请参见下文(您需要包括Jquery库):
JS小提琴
表单请求已停止,因为onSubmit返回false。你需要返回true 检查按键事件的输入值:
<script>
function checkPosX(this) {
if ( parseInt(this.value) > 100 ) {
this.value = "100";
}
}
</script>
<form action="?" id="form1" method="POST">
<input type="text" name="posX" id="formPosX" onkeypress="checkPosX(this)" />
<input type="text" name="posY" id="formPosY" />
<input type="submit" value="Send" />
</form>
函数checkPosX(this){
if(parseInt(this.value)>100){
此值为0.value=“100”;
}
}
那就好好干吧
<script>
function checkPosX(this) {
if ( parseInt(this.value) > 100 ) {
this.value = "100";
}
}
</script>
<form action="?" id="form1" method="POST">
<input type="text" name="posX" id="formPosX" onkeypress="checkPosX(this)" />
<input type="text" name="posY" id="formPosY" />
<input type="submit" value="Send" />
</form>