When a user hits the button, everything works fine. But when they hit enter, the page just reloads. What am I doing wrong?
Here's my full code:
<!doctype html>
<html>
<head>
<title>Fun!</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="" media="print" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<style type="text/css">
body {
font-family: arial;
}
</style>
<script type="text/javascript">
function get() {
$.post('data.php', { name: form.name.value },
function(output) {
$('#age').html(output).show();
}
);
}
</script>
</head>
<body>
<div class="container">
<form action="" name="form" method="post">
<input type="text" name="name" /> <input type="button" value="Get" onClick="get();" />
</form><br />
<div id="age" style="display: none;">Result</div>
</div>
</body>
</html>
Thanks.
You are setting the onclick
event for the button, this will not work when Enter is pressed, because it is not a click.
Take off onclick
and add
onsubmit="event.preventDefault();get();return false;"
to the <form>
.
event.preventDefault();
prevent
s the submission of the form (the Default
action).
return false;
is for older versions of Internet Explorer, because they don't support e.preventDefault();
. Modern browsers ignore return false;
.
When a user presses enter, the form will be submitted. You'll have to look for the onsubmit
event of the form, rather than using the onclick
event of the button.
<form ... onsubmit="get();">
...
</form>
Now you also have to prevent that the page actually submits (because you did it with AJAX). Add return false;
at the end of the function get()
.
It is better practice to assign the event using jQuery (since you are using it anyway), with the on()
method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.