Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset back to previous option on Select field if js Confirm returns false

I have a HTML select field. Where one option is selected. If I select any other change even fires and confirm prompt is shown.

What I want is when user cancel the confirmation aka conf is false. I want to reset back to the previous selected option. But currently the new option is selected.

HTML

<select id="mySelect">
    <option>Foo0</option>
    <option seleted="selected">Foo1</option>
    <option>Foo3</option>
    <option>Foo4</option>
    <option>Foo5</option>
    <option>Foo6</option>
</select>

js/jq

jQuery(document).ready(function($){
   var select = $('#mySelect');
   select.change(function(){
     var conf = confirm('Are You Sure?');
     if(!conf){
         // reset the select back to previous
         return;
     }

     // do stuff

  });
});
like image 271
Sisir Avatar asked Sep 10 '25 11:09

Sisir


1 Answers

I created a jsfiddle for you here: http://jsfiddle.net/CZ8F9/

I am just saving the previous index.

jQuery(document).ready(function($){
   var index = $('#mySelect').prop('selectedIndex'); 
    var select = $('#mySelect');
   select.change(function(e){
       alert(index)
     var conf = confirm('Are You Sure?');
     if(!conf){
             $('#mySelect').prop('selectedIndex',index);
         // reset the select back to previous
         return false;
     }
       else{
       index= $('#mySelect').prop('selectedIndex');}

     // do stuff

  });
});
like image 124
Abs Avatar answered Sep 13 '25 01:09

Abs