form should not submit on enter if focus is not on submit button

二次信任 提交于 2019-12-14 03:15:41

问题


I have a requirement where user cannot submit the form if he press enter key unless focus will be on submit button.

Using following code, I am able to do that, but now the issue is, if I have any enter key event attached specific to any field (e.g. if I want to attach enter key event to one textfield for some special requirement), it is not allowing me due to the script I have written below..

<script>
$(document).keydown(function(event) {
if (event.keyCode == 13) {
    var $focusedItem = $(document.activeElement);
    if($focusedItem.is("button") || $focusedItem.is("a") || $focusedItem.attr("type") == "submit") {
        $focusedItem.click();
    } 
    else {
            event.preventDefault();
         }
    }
});
</script>

Any solution where I can restrict user from submitting form on pressing enter key, if focus is not on the submit button but at the same time if there will be any enter key event attached to any form-field, that should also work.


回答1:


If you had created a JsFiddle it would be easier to help. However, I'm thinking you should do something like this:

if($focusedItem.attr('id') == 'submitButton') {
    if (event.keyCode == 13) {
        submit the form
    }
}else if ($focusedItem.attr('id') == 'Anothertextarea') {
    if (event.keyCode == 13) {
        do something special
    }
}else{
    if (event.keyCode == 13) {
    return null;
    }
}



回答2:


Remove the line event.stopPropagation(); from your script, you need only the preventDefault() (prevents the submit).

When you do stopPropagation() you are stopping all other keypress events on the element.




回答3:


Try that and see if it fits your needs:

--DEMO--

$(document).on('submit', 'form', function (e) {
    e.preventDefault();
}).on('click', ':submit', function (e) {
    if (!$(document.activeElement).is(':submit')) return;
    var form = $(this).closest('form').length ? $(this).closest('form')[0] : $('#' + $(this).attr('form'))[0];
    form.submit();
});



回答4:


Maybe I'm missing the point, this is basically a standard html issue.

Don't give the form an submit action (move it to a click event directly on the button) and change all button types to button instead of submit.

I can't remember if simply removing the submit from the form is enough. If not then just do onSubmit="return false;" I think that does it.

However as a note the requirement for this as a global behavior is probably wrong and if its for the government then you will probably get in trouble since its not compliant with accessibility guidelines.



来源:https://stackoverflow.com/questions/23501167/form-should-not-submit-on-enter-if-focus-is-not-on-submit-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!