2

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()?

3 Answers 3

5

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(){});
Sign up to request clarification or add additional context in comments.

2 Comments

Than you have another problem.
Wow... Missed that typo there... Thank you for spotting that for me!
3

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/

Comments

0

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

2 Comments

That is what I tried at first but still no luck. I am using the $(document.ready(function() somewhere else on a previous page. Could that be part of the problem?
Yes. Look at the fix: jsfiddle.net/shrimpboyho/AFbEL/1 That is how document ready should be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.