简体   繁体   中英

keep previously selected value in dropdown jquery

I am trying to keep the same option value selected even after the click on dropdown, but It just keeps on saying undefined. Here is my code:

  var previous_value; $(".acc").on('shown.bs.select', function(){previous_value = this.value;}).change(function() { if($('img').is(':visible')){ if(window.confirm('Please save or data is lost')){ var t = $('.acc option:selected').val() alert(t); }else { //code here } } else { //code here } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img class = "<?php echo $i ?>" src="" alt="" height="22" width="30"> <br/> <label> AD Mgr </label><br/> <select class = "acc" > <option value="1" selected>1</option> <option value="2">2</option> <option value="3">3</option> </select> 

Thank you

I'm not familiar with bootstrap so I can't explain this point but, clearly, the issue in your case is that on('shown.bs.select', ...) doesn't fire, so previous_value remains undefined .

Nevertheless the solution to match your need is pretty simple: you must unconditionally set previous_value at start.

Here is a modified version of your code, where not only alert() shows new and previous values, but also the dropdown remains always unchanged, like you ask for:

 var previous_value = $(".acc").change(function() { if ($('img').is(':visible')) { if (window.confirm('Please save or data is lost')) { var t = $('.acc option:selected').val(); alert('New value: ' + t + '\\nPrev value: ' + previous_value); $(this).find('option[value=' + previous_value + ']').prop({selected: true}); } else { //code here } } else { //code here } }) .val(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img class = "<?php echo $i ?>" src="" alt="" height="22" width="30"> <br/> <label> AD Mgr </label> <br/> <select class="acc"> <option value="1" selected>1</option> <option value="2">2</option> <option value="3">3</option> </select> 

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