How can I disable the ENTER key on my textarea?

2020-05-23 11:04发布

问题:

<form name='qform'>
<textarea name='q' rows='3' cols='60' wrap='hard' id='q' onkeydown="if (event.keyCode == 13) document.getElementById('clickit').click()"></textarea>
<input type='button' value='search' id='clickit' onclick="get();">
</form>

I have this form... it doesn't have a submit button because I am using jquery and under this form is a div area where the results will be shown. It is a search engine that does not have an input box but instead has a textarea. This is because it will be a multiple word searcher.

The problem is that if I press enter, the query is submitted and everything is ok ... but the focus on textarea goes down one line and that is a problem for me.

Basically I want the enter to have that one function only(submit) end nothing else.

回答1:

In the jquery function, use event.preventdefault and next do what you like. For example

<script>
$("a").click(function(event) {
  event.preventDefault();
//Do your logic here
});
</script>

http://api.jquery.com/event.preventDefault/



回答2:

$(document).ready(function() {

    $('textarea').keypress(function(event) {

        if (event.keyCode == 13) {
            event.preventDefault();
        }
    });
});


回答3:

Why not just use <input type="text"> if you don't want multiple lines? You mentioned it will be a "multiple word searcher". Why does this require a <textarea>?

Update

Try this

$('textarea').bind('keypress', function(e) {
  if ((e.keyCode || e.which) == 13) {
    $(this).parents('form').submit();
    return false;
  }
});