Erik Dekker
Erik Dekker

Reputation: 2433

How to click a button through a shortcut with javascript without causing a page reload

I need some shortcuts in my web application, that will do the same as when a user clicks on a button, or presses the button with the accesskey.

I simplified my code to show you my problem:

<html>
<head><script src="jquery-1.4.2.js" type="text/javascript"></script></head>
<form>
    <body>
        <div id="myDiv">text</div>
        <input name="cmdChangeText" type="submit" value="change text" onclick="document.getElementById('myDiv').innerText='text is changed'; return false;" />

        <input name="cmdTestButton" type="submit" value="hello" onclick="alert('hello'); return false;" accesskey='z' />
    </body>
</form>
<script type="text/javascript">
    document.onkeydown = function() {
        if (event.keyCode == 83) { //83 = 's'
            window.$('[accesskey=z]').click();
        }
    }
</script>
</html>

The first button changes the text. When you click the second button, or click it through accesskey (Alt + Z in IE), you get the alert, but the page does not reload: the text is still changed!

When I press some button, the S in this example, I do get the alert, but the page gets reloaded! Why is the return false; ignored this way, and what can I do about it?

Upvotes: 1

Views: 3796

Answers (2)

Art
Art

Reputation: 24597

I would get rid of the onclick="alert('hello'); return false" stuff and attach events using jQuery.

After that, you can try cancel the event bubbling:

$('#myInput2').click(
    function() {
        alert('hello')
        return false
    }
 )

Just a hunch.

Upvotes: 3

baked
baked

Reputation: 245

Give the buttons different names, in this example I have used 'test1' and 'test2' and add the following code.

$('input[name=test1]').click( function(e){
    e.preventDefault();
    $('#myDiv').innerText('text is changed');
});

$('input[name=test2]').click( function(e){
    e.preventDefault();
    alert('hello');
});

An input of type 'submit' will submit the page by default. Using 'preventDefault()' method on the event will, unsurprisingly prevent the default action. If you want the page to reload just remove this line.

Upvotes: 0

Related Questions