简体   繁体   中英

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/

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.

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')
});

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.

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')
    })
})

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM