views:

65

answers:

3

I'm trying to get an alert message with Yes/No option, where clicking on 'Yes' reloads a another drop-down option, and 'No' would revert back to the previous selection. Here is what I'm trying to say (obviously doesn't work):

<select size="1" name="m" id="m">  
    <option selected value="1">apple</option>
    <option value="2">ball</option>
    <option value="3">cat</option>
    <option value="4">dog</option>
    <option value="5">egg</option>
</select>

$('#m').change(function() {
    var answer = confirm("this will change your selection.");
    if (answer) { // ie, if i click 'OK'
        location.reload(); // reload the <select> option below to "selected"
    } else {
        break; // revert back to the previous selection
    }
});


<select size="1" name="a" id="a">  
    <option selected value="1">aaa</option>
    <option value="2">bbb</option>
    <option value="3">ccc</option>
</select>

Many thanks in advance. Feel free to click, and edit.

+2  A: 

JavaScript's confirm() only displays OK and Cancel, not Yes or No.

Could you return false instead of break, because you are in a function?

Also, returning false does not cancel the change event. What you will need to do is store the previous selectedIndex, and if you have the confirm() return false, then set the selectedIndex back to the previous one.

Also, I hope you are wrapping that jQuery inside script elements and inside a $(document).ready().

alex
Thank you for you help.
DGT
+2  A: 

I'm not too sure what you are trying to accomplish... is it this?

var _selected = $('#m').val();
$('#m').change(function() {
    var answer = confirm("this will change your selection.");
    if (answer) { // ie, if i click 'OK'
        _selected = $(this).val();
        $('#a').val(_selected);
    } else {
        $(this).val(_selected);
    }
});​
Yanick Rochon
I think this is the correct answer, i was going to post the exact same solution!
David Conde
Yes, that's it. Thanks so much. Btw, it works fine on firefox, but not quite right on Chrome. The second select value doesn't quite refreshes to the default "selected" option, in fact it goes blank, for some reason.
DGT
@DGT, it should work alright in any browser since you're using JQuery. The problem is that your two SELECT elements don't have the same amount of OPTION values. you can check if a select has a given value with $('#a').find("option[value='" + _selected + "']").size() > 0 or checking if $('#a').val() == null after setting it's new value.
Yanick Rochon
A: 

Try removing the

break;

I tried to run the code and Firebug halts the code when it gets to that part

Best regards,

David Conde