Below is the example of the code for the scenario.
<select 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
CodePudding user response:
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 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>