Search code examples
javascriptjqueryhtmllistboxconfirm

How to prevent changing of select option after cancelling confirm using jquery?


So I have an select option field, and what I change the option of select field a confirm message will show. My problem is how do I prevent of changing the value of select option field after cancelling the confirmation message.

$('.changeScoreFem').on('change', function(){
    if (confirm('Are you sure to change this score?')) {
        //continue to change  the value
    } else {
        //else do not change the selecoption field value
    }
});

Solution

  • You can do this by storing current value of select, then undo it as needed.

    Following uses a custom event to store the data and that custom event is also triggered on page load in case you pass selected items from server

    var $sel = $('.changeScoreFem').on('change', function(){
        if (confirm('Are you sure to change this score?')) {
            // store new value        
            $sel.trigger('update');
        } else {
             // reset
             $sel.val( $sel.data('currVal') );        
        }
    }).on('update', function(){
        $(this).data('currVal', $(this).val());
    }).trigger('update');
    

    DEMO