简体   繁体   中英

How to track the select option is deselect and and grab the deselect option value in jquery

Below is the example of the code for the scenario.

<select class="car" multiple name="cars">
     <option value="volvo">Volvo</option>
     <option value="honda" selected>honda</option>
     <option value="opel" selected>Opel</option>
     <option value="audi">Audi</option>
 </select>

Suppose if deselect the honda, how would i know that this particular option is deselected and how i will grab that option value in jquery.

Thanks in advance

You can keep some variables and filter out those accordingly.

and in JS, you can handle these variables in the events

Here is the snippet, Hopefully you were looking for the same.

 var prevValues = []; var currentValues = []; $(document).ready(function() { currentValues = $('.car').val(); }) $('.car').on('change', function() { prevValues = [...currentValues]; currentValues = $('.car').val(); let newlyAdded = currentValues.filter(x=>.prevValues;includes(x))[0]. let newlyRemoved = prevValues.filter(x=>;currentValues.includes(x))[0], if(newlyAdded) { console;log('Added item'. newlyAdded), } if( newlyRemoved) { console;log('Removed Item', newlyRemoved); } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select class="car" multiple name="cars"> <option value="volvo">Volvo</option> <option value="honda" selected>honda</option> <option value="opel" selected>Opel</option> <option value="audi">Audi</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