Tim Hall
Tim Hall

Reputation: 3

Why does my enterbutton refresh my page?

Here is my Jquery code for my "site".

$(document).ready(function() {
$('#val').click(function() {
    var toAdd = $("input[name=message]").val();
    $('#messages').append("<p>"+toAdd+"</p>");
    $('#messages').val(""); //remove text in textbox//  
});

$('#kor').click(function() {
var random = Math.floor((Math.random()*$("#messages>p").length));

alert($("#messages>p").eq(random).text());
});
});

I got a textbox and when pressing "#val" it adds whats in the text box to a "pool" where it sooner will randomly choose something in the pool.

My problem is when hitting the Enter key, my page reload. I would like to bind my enter button to "#val" or disable it. Cause pressing enter and reload page is pretty annoying.

Upvotes: 0

Views: 42

Answers (1)

Jeremy Thille
Jeremy Thille

Reputation: 26360

As adeneo said, you have to prevent the default behaviour of the Enter key, which is submitting the form. But he didn't say how :) Here's how :

$('#val').click(function(e) {
    e.preventDefault();
   /* some other stuff */
})

Upvotes: 2

Related Questions