I need to select only 3 options from the multiple select. If user selects more than 3 options than the last selected element should be replaced by the new one clicked.
I have a example as follows:
<select multiple id='testbox'>
<option value='1'>First Option</option>
<option value='2'>Second Option</option>
<option value='3'>Third Option</option>
<option value='4'>Fourth Option</option>
<option value='5'>Fifth Option</option>
<option value='6'>Sixth Option</option>
<option value='7'>Seventh Option</option>
<option value='8'>Eighth Option</option>
<option value='9'>Ninth Option</option>
<option value='10'>Tenth Option</option>
</select>
When user selects
First option
Second option
Third option
Now he reaches max selection limit 3 .If he click on the another option like Tenth Option I need to remove Third option and get selected Tenth option
For that i tried this but no idea how I can achieve my goal
<script type="text/javascript">
google.load("jquery", "1");
$(document).ready(function() {
//alert("1111");
var last_valid_selection = null;
$('#testbox').change(function(event) {
if ($(this).val().length > 2) {
alert('You can only choose 2!');
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
latest_value = $("option:selected:last",this).val()
alert(latest_value);
}
});
});
</script>
Please suggest some idea or solution.
If we want to remove multiple specified items from dropdown then we can use jQuery's filter() method as $('#ddlItems option'). filter('[value="1"],[value="2"],[value="5"]'). remove();Assuming we want to delete item with values 1,2 and 5.
With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.
The task is to remove the option elements from the select element using jQuery. Approach: Select the option from select which needs to remove. Use JQuery remove() method to remove the option from the HTML document.
This works quite nicely:
var lastSelected;
$("#testbox").change(function() {
var countSelected = $(this).find("option:selected").length;
if (countSelected > 3) {
$(this).find("option[value='" + lastSelected + "']").removeAttr("selected");
}
});
$("#testbox option").click(function() {
lastSelected = this.value;
});
I had to set a global variable lastSelected
as well as an options click event to capture the actual last option clicked (this.value
in the change event was giving me the top selected option, not the actual last option).
Demo: http://jsfiddle.net/JAysB/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With