jQuery how to undo a select change

Viewed 61277

I have a select box, and I'd like to add a confirm before changing it to a specific option. Example:

<select name="select">
    <option value="foo" selected="selected">foo</option>
    <option value="bar">bar</option>
</select>​​​​​​​​​​​​​​​​​​
$('select').change(function() {
    var selected = $(this).val();

    if (selected == 'bar') {
        if (!confirm('Are you sure?')) {
            // set back to previously selected option
        }
    }
});

I'm thinking about adding a hidden input field and update its value every time the select is changed. That way I can retrieve the previous value in the change function. Example:

<input type="hidden" name="current" value="foo" />
$('select').change(function() {
    var selected = $(this).val();
    var current = $('input[name=current]').val();

    if (selected == 'bar') {
        if (!confirm('Are you sure?')) {
            $(this).val(current);
            return false;
        }
    }

    $('input[name=current]').val(selected);
});

Is there an easier/better way to accomplish this?

7 Answers

$(document).on('change','.change_response_status',function()
{
    var responseStatusId = this.id;
    var responseID = $("#"+responseStatusId).attr('data-id');
    var previouesSatatus = $("#hidden_response_id_"+responseID).val();
    var confirmstatus = confirm("Are you sure you want to change status for this item?");
    var currentSelectedValue = $(this).val();

    if(confirmstatus==true)
    {
        $("#hidden_response_id_"+responseID).val(currentSelectedValue);
    }
    else
    {
        $(this).val(previouesSatatus);
        $("#hidden_response_id_"+responseID).val(previouesSatatus);
        return false;
    }
    return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select data-id="2" id="response_id_2" class="change_response_status" name="status">
    <option value="1">Accept</option>
    <option value="2" selected="selected">No Respond</option>
    <option value="3">Reject</option>
</select>
<input class="hidden_response_class" id="hidden_response_id_2" type="hidden" value="1" name="hidden_response_staus">

This is best way to display already selected option on click with using cancel on confirmation box.

If you are using Select2, you can use something below,

$('select').on('select2:selecting', function() {
    if (!confirm('Are you sure you?')) {
         $(this).select2('close')
         return false
    }
})
Related