Enter to submit rather than refresh [duplicate]
Possible Duplicate:
Enter button on Keyboard refreshes rather than submitting
I have the following form structure
structure of my form:
<form name="form">
<label>Name:</label>
<input type="text" name="name" id="id" size="50"/></br>
<label></label>
<input type="button" value="Get Info" onClick="get();">
</form>
&l开发者_如何学JAVAt;div id="age"></div>
My javascript for the get function is as follows:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
}
Now when i use button(input type="button") to post information it works well,But when i fill the information and press enter on the keyboard page gets refreshed.
How can i make Enter button to post the info?
Many times the default behavior in a form
when enter is pressed in a non-textarea field is to submit, even when a submit button was not pressed or even present.
Try this:
<form name="form" onsubmit="get();return false;">
In fact, using this technique, you would be able to change your input button
to a submit to simplify the form with the same outcome:
<input type="submit" value="Get Info"/>
try return false;
in your function. This will stop the button from having its usual behaviour:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
return false;
}
I do it a little differently (which probably means its the wrong way). I dont make a form at all. I just create inputs, selects, etc.. and then when i do my POST i just get the values wen the function is called..
$.ajax({
type: "POST",
url: "someFile.php",
data: { 'name': $("#ElementID").val()},
success: function(data) {
//some function....
{
});
Hope that may be helpful....
I see you posted this as jQuery so I figured I'd give you a solution using that.
$('form[name=form]').submit(function(e) {
var $form = $(this);
$.post( $form.attr('action'), $form.serializeArray(), function( result ) {
$('#age').html( result ).show();
});
e.preventDefault();
});
This will keep you from having to create a crazy json object for the data parameter and from repeating yourself with the form's action attribute. This will also keep the browser's behavior where pressing enter when on an input will submit the form.
Here goes some code I have from an example earlier. The only thing in the form's action file is <?php print_r($_POST); ?>
.
精彩评论