2010-01-12 9 views
25

Estoy usando una etiqueta de selección en un formulario que estoy haciendo que permite selecciones múltiples, pero quiero hacer la cantidad máxima de selecciones hasta 10. ¿Es posible usar javascript o jquery?¿Cómo se limitan las opciones seleccionadas en un cuadro de selección html?

¡Gracias de antemano!

+0

Bienvenido a stackoverflow, Tominated! – Sampson

+0

OK, lo pondré más en contecto. es un formulario de correo electrónico interno de la empresa con un cuadro de selección generado automáticamente con el nombre de cada empleado. Lo estoy actualizando para que muestre los nombres que ya ha seleccionado (es una lista looooooong) y hay alguna validación del cliente de que no ha seleccionado más de 10 nombres (obviamente, hay un código lateral para evitar esto) . La identificación para la etiqueta de selección es "recipient_userid". Voy a publicar lo que tengo hasta ahora – tominated

+0

$ (document) ready (function() { \t \t var last_valid_selection = null;. \t $ ("# recipient_userid") cambio (function (event) { \t \t \t var seleccionada = ""; \t \t \t \t $ ("# recipient_userid opción: seleccionado"). each (function() { \t \t \t seleccionado + = "

  • " (este) .text + $ () + "
  • "; \t \t}); \t \t \t \t $ ("# currentlySelected") html (seleccionado).; \t \t \t}). Change(); }); – tominated

    Respuesta

    29

    Aquí hay un código completo para que usted ... te va a encantar la API de Google AJAX juegos :-)

    Edición 1: Nota: esto sólo le permite elegir 5 porque yo no' t siento como copiar/pegar otros 10 opciones :-)

    <!-- 
        copyright (c) 2009 Google inc. 
    
        You are free to copy and use this sample. 
        License can be found here: http://code.google.com/apis/ajaxsearch/faq/#license 
    --> 
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
        <head> 
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/> 
        <title>Sample Select Maximum with jQuery</title> 
        <script src="http://www.google.com/jsapi?key=ABQIAAAA1XbMiDxx_BTCY2_FkPh06RRaGTYH6UMl8mADNa0YKuWNNa8VNxQEerTAUcfkyrr6OwBovxn7TDAH5Q"> </script> 
        <script type="text/javascript"> 
        google.load("jquery", "1"); 
    
        $(document).ready(function() { 
    
         var last_valid_selection = null; 
    
         $('#testbox').change(function(event) { 
         if ($(this).val().length > 5) { 
          alert('You can only choose 5!'); 
          $(this).val(last_valid_selection); 
         } else { 
          last_valid_selection = $(this).val(); 
         } 
         }); 
        }); 
        </script> 
        </head> 
        <body style="font-family: Arial;border: 0 none;"> 
        <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> 
        </body> 
    </html> 
    

    Demo

    +0

    ¡eso es casi perfecto! no lo selecciona de nuevo si last_valid_selection es una matriz. ¡Gracias, sin embargo! – tominated

    +0

    No estoy seguro de lo que quieres decir. ¿Qué no lo selecciona de nuevo si 'last_valid_selection' es una matriz? –

    +0

    Es posible que desee mover 'last_valid_selection' fuera del alcance global y en la función anónima' ready'. –

    3

    Usando jQuery puede adjuntar una función al evento de cambio y dado que es una selección múltiple, val() será una matriz. Siempre puede verificar la longitud de la matriz y hacer algo si es un tamaño predefinido. El siguiente código demuestra cómo sabrá cuántos elementos se seleccionan.

    $("#select").change(function(){ 
         alert($(this).val().length); 
        }); 
    
    +0

    que ayudará mucho. ¿Hay alguna manera de deseleccionar todo en un cuadro de selección, también? – tominated

    +0

    @tominated - Usando jQuery, puede simplemente llamar a '$ ('# myselectbox_id'). Val (null);' –

    +0

    Puede usar esto: '$ (" # select "). Val ([]);' para establecer no hay opciones en la lista de selección. –

    15

    Esto limitaría al usuario 3 opciones:

    $("select").on("click", "option", function() { 
        if (3 <= $(this).siblings(":selected").length) { 
         $(this).removeAttr("selected"); 
        } 
    });​​​​​​​​​​ 
    

    violín: http://jsfiddle.net/2GrYk/

    +0

    gran solución - ¡simple y al grano! gracias :) –

    +7

    Esto no funcionará si usamos el teclado, o un clic de planeo. – zessx

    2

    lo descubrió! aquí está el código resultante:

    $(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 += "<li>" + $(this).text() + "</li>"; 
         }); 
    
         $("#currentlySelected").html(selected); 
         selected = ""; 
        } 
    
    }).change(); 
    }); 
    

    Gracias por toda su ayuda chicos!

    +2

    Tominated, esto no es un foro. Tus contribuciones solo deberían existir en la pregunta original (puedes editarla tanto como quieras). Debería aceptar una de las muchas buenas respuestas que se proporcionaron aquí. – Sampson

    +0

    Tominated, Jonathan es absolutamente correcto. La idea es hacer una pregunta y seleccionar la mejor respuesta (incluso se gana una reputación por hacerlo). Muy rara vez selecciono una respuesta, y aún más raro es que responda mi propia pregunta. Sin embargo, esta comunidad está aquí para ayudarse entre sí, y me alegra que hayamos ayudado. –

    +0

    Lo siento muchachos, no estaba al tanto de eso. – tominated

    0

    Puede usar jQuery

    $("select").change(function() { 
         if($("select option:selected").length > 3) { 
          //your code here 
         } 
        }); 
    
    1

    Yo, básicamente, fusionado a un par de las respuestas dadas a hacer algo específico para un determinado ID:

    $("#mySelect").on("click", "option", function(){ 
        var max = 3; 
        if (max <= $(this).siblings(":selected").length) { 
         alert("Only " + max + " selections allowed."); 
         $(this).removeAttr("selected"); 
        } 
    }); 
    

    Rob

    4

    Esta respuesta funciona en aquellos casos:

    • Haga clic en Normal
    • Sólo mousedown (ratón se mueve fuera antes mouseup)
    • teclado
    • Si hay diferentes opciones con el mismo valor

    Código:

    $('#mySelect').on('change', function() { 
        if (this.selectedOptions.length < 4) { 
         $(this).find(':selected').addClass('selected'); 
         $(this).find(':not(:selected)').removeClass('selected'); 
        }else 
         $(this) 
         .find(':selected:not(.selected)') 
         .prop('selected', false); 
    }); 
    

    Demo

    O, para navegadores antiguos que no son compatibles con selectedOptions,

    $('#mySelect').on('change', function() { 
        var $sel = $(this).find(':selected'); 
        if ($sel.length < 4) { 
         $sel.addClass('selected'); 
         $(this).find(':not(:selected)').removeClass('selected'); 
        }else 
         $(this) 
         .find(':selected:not(.selected)') 
         .prop('selected', false); 
    }); 
    

    Demo

    0

    Voila! No es necesario Jquery.

    var is = 0; 
        for (var i = 0; i < selectCountryCode.length; i++) { 
         if (selectCountryCode.options[i].selected) { 
          is++; 
         } 
         if (is > 3) { 
          selectCountryCode.options[i].selected = false;    
         } 
        } 
    

    Jilusan

    +0

    Este ejemplo parece incompleto, quizás por intención, ya que implicaría jQuery? ¿Qué es selectCountryCode? – Lev

    Cuestiones relacionadas