简体   繁体   中英

Bind jQuery click event to regular javascript button

I'm trying to create a simple function in jquery to direct the user's browser to the previous page if the Cancel button is clicked but I'm a bit mythed as to how to do it since I have minimal experience of jquery.

<input type="button" id="cancelBc2" name="cancelForm" value="Cancel">
$(document.ready(function() {
    $('cancelBc2').click(function() {
        var cancel = confirm("Are you sure you want to leave the page?");
        if (cancel == true) {
            window.location = "chooseConfig.php";
        }
    });
});

Am I missing something or is the page just completely overlooking the

$(document.ready(function()?

You are missing the # on the selector

$('cancelBc2')  //looking for an element <cancelBc2 />
$('#cancelBc2')  //looking for an element with id="cancelBc2"

And you have a typo

$(document.ready

should be

$(document).ready(function()

even better

$(function(){});

Should add prefix # to select Id in jQuery

$('#cancelBc2').click(function() {
    var cancel = confirm("Are you sure you want to leave the page?");
    if (cancel == true) {
        window.location = "chooseConfig.php";
    }

});

For information: http://api.jquery.com/id-selector/

Your code is good, but you are missing the proper selector. It should be $('#cancelBc2')

This selects the element in the DOM with the id cancelBc2

For a full list of jQuery selectors utilize this:

http://www.w3schools.com/jquery/jquery_ref_selectors.asp

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