1

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 to 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.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Samuel Meddows
  • 36,162
  • 12
  • 38
  • 36

3 Answers3

2

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);
        });
    }
});
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1
$(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.

Gazler
  • 83,029
  • 18
  • 279
  • 245
-1

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; }); });

Samuel Meddows
  • 36,162
  • 12
  • 38
  • 36
  • 1
    This will prevent pressing enter on all inputs. You should change $('input') to $('input[type=text]') – Gazler Dec 01 '10 at 14:03