Consider the following event:
$(`#selectpicker).on('change', function(){
if(condition) {} else
{
//canceel event change
}
});
How to cancel the change event based on specific condition therefore maintaining the same select picker value.
Is this what you are looking for? Set a variable for the current value and if an undesired value is selected we set the value of the select field back to the recent value.
<select id="selectpicker">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
let currentValue = $('#selectpicker').val();
$('#selectpicker').on('change', function(){
let newValue = $(this).val();
if(newValue == 3){
console.log("3 is not allowed");
$(this).val(currentValue);
return;
}
currentValue = $('#selectpicker').val();
})
You could also disable certain options with "disabled" keyword, but keep in mind that this can be easily bypassed from developer tools.
<option disabled value="3">3</option>
While you can stop the execution of the callback with return false, the value will already have changed when this event is triggered. If you want to return to the previous value, you have to store it somehow, either in a variable or in a data property on the element. Then you can set the value back in your condition, or update the variable when your cancel-condition is not met.