user1050619
user1050619

Reputation: 20856

Type = button, Onclick vs Onsubmit

I have created a simple submit button and trying to trigger the click and submit event but both are not working...

html

<input type="submit" id="test">

JQuery:

$(document).ready(function(){
    $('#test').onclick(function(){
        alert('Hi')
})

    $('#test').click(function(){
        alert('Hi')
})

    $('#test').onclick(function(){
        alert('Hi')
})
})

fiddle http://jsfiddle.net/x57Lj/

Upvotes: 0

Views: 112

Answers (5)

Raj Nathani
Raj Nathani

Reputation: 2845

Problem: the function onclick() does not exist in jQuery.

Simply replace onclick() with click() Here is an example of your jsfiddle with not 1, but 2 event callbacks for 'click' :)

http://jsfiddle.net/x57Lj/3/

$(document).ready(function () {
    $('#test').click(function () {
        alert('Hi')
    })
    $('#test').click(function () {
        alert('Hi2')
    })
})

Upvotes: 0

Alexey Dmitriev
Alexey Dmitriev

Reputation: 163

Handle form submit with submit event. In case 'onclick' event it's not handle return button press.

Upvotes: 0

joelmdev
joelmdev

Reputation: 11773

Use the click function, not onclick. There is no onclick function in jQuery. onclick is an HTML event attribute you use to wire up a DOM element to a pure javascript function.

So if using jQuery you want the following:

$('#test').click(function(){
    alert('Hi');
});

which is equivalent to

$('#test').on('click', function(){
    alert('Hi');
});

in case you're wondering.

Upvotes: 0

Madnx
Madnx

Reputation: 1564

You should use "on" and e.preventDefault(); to prevent page for reloading.

$('#test').on('click', function(e){
    e.preventDefault();
    alert('Hi')
});

or:

$('#test').click(function(e){
    e.preventDefault();
    alert('Hi')
});

Upvotes: 0

Paul S.
Paul S.

Reputation: 66304

You mean to use jQuery's .on

jQueryObject.on('click', handler);

The onclick property of jQuery objects is not the same as that on a HTMLElement, remember they're different things.

Upvotes: 1

Related Questions