javascript - Remove last selected element from the multiple select if user select more than 3 option using jquery -


i need select 3 options multiple select. if user selects more 3 options last selected element should replaced new 1 clicked.

i have example 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 reaches max selection limit 3 .if click on option tenth option need remove third option , selected tenth option

for tried no idea how can achieve 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 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 idea or solution.

var lastopt; $('#testbox option').click(function () {     lastopt = $(this).index(); }); $('#testbox').change(function () {     if ($('option:selected', this).length > 3) {         $(' option:eq(' + lastopt + ')', this).removeattr('selected');     } }); 

jsfiddle


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -