这可能有点棘手。
我有一个包含 10 个文本框的表单(考虑它的 name1、name2 .. name10)
我想要的是当我关注 name1
文本框并点击“输入”时,不应提交表单。相反,我想调用一个函数。
但是当我在关注其他表单元素而不是 name1
时点击“enter”时,应该会提交表单。
如果您认为有任何其他想法可以做到这一点,请建议我。
注意:我无法将元素移出表单。
最佳答案
对第一个输入元素使用按键事件,并使用 event.preventDefault();
阻止表单提交
$(document).ready(function() {
$("#name1").keydown(function(event){
if(event.keyCode == 13) {
calculate() // call your function here
event.preventDefault();
}
});
$( 'form' ).on( 'submit' , () => { // arrow function
console.log("submited"); // form
} );
function calculate() {
console.log("prevent submitting");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.js"></script>
<form>
<input id="name1" type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="submit" value="Go">
</form>
关于javascript - 当我在特定表单元素上单击 "enter"时拒绝提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58671745/