How do you limit options selected in a html select box?

后端 未结 8 831
一生所求
一生所求 2020-11-27 19:07

I\'m using a select tag in a form I\'m making that allows multiple selections, but I want to make the maximum amount of selections upto 10. Is this possible using javascript

8条回答
  •  醉梦人生
    2020-11-27 19:30

    figured it out! here's the resulting code:

    $(document).ready(function(){
    
    var last_valid_selection = null;
    var selected = "";
    
    $("#recipient_userid").change(function(event){
    
        if ($(this).val().length > 10) {
    
            alert('You can only choose 10!');
            $(this).val(last_valid_selection);
    
        } else {
    
            last_valid_selection = $("#recipient_userid").val();
    
            $("#recipient_userid option:selected").each(function () {
                selected += "
  • " + $(this).text() + "
  • "; }); $("#currentlySelected").html(selected); selected = ""; } }).change(); });

    Thanks for all your help guys!

提交回复
热议问题