简体   繁体   中英

Cancel button not working for the confirm window

I'm trying to validate radio buttons in JavaScript and this is my code:

if (document.ExamEntry.GCSE.checked == true) {
    confirm("You have selected GCSE. Is this correct?");
}
if (document.ExamEntry.AS.checked == true) {
    confirm("You have selected AS. Is this correct?");
}
if (document.ExamEntry.A2.checked == true) {
    confirm("You have selected A2. Is this correct?");
}

The confirm window shows up and clicking 'Submit' successfully takes you to the next page, however the cancel button doesn't seem to work - it just takes you to the next page when I want it to stay on the page so you can change your option.

I've tried things such as return result; result = false

They either don't work, or if they do, then it's vice versa so that the cancel button works by staying on the same page, but this will happen with the submit button too.

Check out the documentation on confirm . It says,

result is a boolean value indicating whether OK or Cancel was selected (true means OK)

That means each of your lines should check the return value. A concise way to do this is, eg:

if (!confirm("You have selected A2. Is this correct?")) {
    // event.cancel = true, or whatever you need to do on your side to cancel
} // otherwise fall through and do what you're doing.

As it is right now, since you never look at the return value of confirm , so you always fall through to your "success" case.

var gcse = true, 
    as   = true,
    a2   = true;

if (document.ExamEntry.GCSE.checked == true) {
    gcse = confirm("You have selected GCSE. Is this correct?"));
}

if (document.ExamEntry.AS.checked == true) {
    as = confirm("You have selected AS. Is this correct?");
}

if (document.ExamEntry.A2.checked == true) {
    a2 = confirm("You have selected A2. Is this correct?");
}

if (gcse && as && a2) {
    // you're golden
    window.location.href = 'otherpage'
}
if (document.ExamEntry.GCSE.checked == true) { 
    if(confirm("You have selected GCSE. Is this correct?")) {
        // do something
    }
} if (document.ExamEntry.AS.checked == true) {
    if(confirm("You have selected AS. Is this correct?")) {
        // do something
    }
}  
if (document.ExamEntry.A2.checked == true) {
    if(confirm("You have selected A2. Is this correct?")) {
        //do something
    }
}

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