这可能有点棘手。
我有一个包含10个文本框的表单(考虑其name1,name2 ..name10)
我想要的是当我专注于name1
文本框并单击“输入”时,不应提交该表单。相反,我想调用一个函数。
但是当我在聚焦其他表单元素而不是name1
的同时点击“ enter”时,表单应该提交。
如果您认为还有其他想法可以提出建议。
注意:我无法将元素移到表单之外。
答案 0 :(得分:2)
对第一个输入元素使用keypress事件,并通过使用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>
答案 1 :(得分:0)
$('form').on('keypress', function(e) {
if (e.code === 'Enter' && $(e.target).is('textarea')) {
return false;
}
});