开发者

Disable the enter key on a jquery-powered form

开发者 https://www.devze.com 2023-01-28 00:35 出处:网络
I have a form using the form jQuery plug in to handel the posting of the data. In the example i am working with the data is psoted to another php file which reades a database and echos back a result w

I have a form using the form jQuery plug in to handel the posting of the data. In the example i am working with the data is psoted to another php file which reades a database and echos back a result which is displayed below the from.

The code works very well with one glitch. If you hit the enter button while the text filed is selected everything cleared including the result that has been written to the screen. Is it possible to disable t开发者_StackOverflow中文版o enter key and prevent it from doing this?

FORM:

<html>
<head>
</head>
<p>enter code here
<form name="form" action="" method="">
  <label for="name" id="name_label">Name</label> 
  <input type="text" name="name" id="name"/>
  <input type="button" value="get" onclick="get();"/>
</form>

<div id="age"></div>
</p>
</body>
</html>

SCRIPT:

function get() {
    $.post('data.php', {name: form.name.value},
        function(output) {
            $('#age').hide().html(output).fadeIn(1000);
        });
    }
}

Cheers.


You should consider using the jQuery Forms Plugin. It will save you from doing some of the dirty work, additionally it will intercept all ways of submitting the form - so instead of having to disable the RETURN key it will submit your form via AJAX.

If you don't want that, get rid of the button with the onclick event and replace it with a submit button and register your function as a onsubmit handöer:

$('form[name=form]').submit(function(e) {
    e.preventDefault();
    $.post('data.php', {name: form.name.value},
        function(output) {
            $('#age').hide().html(output).fadeIn(1000);
        });
    }
});


$(document).ready(function(){   
    $('form').submit(function(){
        return false;
    });
});

This will prevent the form from submitting, however the form will not work at all for users with javascript disabled.


A found some tuts and solved the issue.

I just put this in before my Jquery code to disable the enter button.

$(function () { $('input').keypress(function (e) { var code = null; code = (e.keyCode ? e.keyCode : e.which); return (code == 13) ? false : true; }); });

0

精彩评论

暂无评论...
验证码 换一张
取 消