Reputation: 3628
I'm finding that when I submit my form by pressing the enter key, the page refreshes (because my form doesn't specify an action), but if I click the button, it executes the jQuery.
How can I make an enter key press execute the jQuery as well?
Here's my code:
<form id="signup-form">
<input type="text" id="text-input-splash" class="text-input" placeholder="Enter your email"><button type="button" id="submit-input-splash">Sign me up</button>
</form>
<p id="validation-message"></p>
<p>100% private and free. No spam. One-click unsubscribe.</p>
<script>
$(document).ready(function(){
$("#submit-input-splash").click(function() {
// import email variable
var email = $("#text-input-splash").val();
$.post("signup.php", {email: email}, function(data){
$("#validation-message").text(data).addClass("error-text");
});
});
});
</script>
Upvotes: 2
Views: 649
Reputation: 337560
To both solve the issue and improve your logic, change your button to a type="submit"
and hook the event handler to the submit
event of the form. Try this:
<form id="signup-form">
<input type="text" id="text-input-splash" class="text-input" placeholder="Enter your email">
<button type="submit" id="submit-input-splash">Sign me up</button>
</form>
<p id="validation-message"></p>
<p>100% private and free. No spam. One-click unsubscribe.</p>
$(document).ready(function(){
$("#signup-form").submit(function(e) {
e.preventDefault();
var email = $("#text-input-splash").val();
$.post("signup.php", { email: email }, function(data) {
$("#validation-message").text(data).addClass("error-text");
});
});
});
Upvotes: 5