2009-08-14 15 views
12

Decir que tengo esta lista desplegable:jQuery eliminar opciones seleccione Basado en otra Seleccione seleccionado (Necesita soporte para todos los navegadores)

<select id="theOptions1"> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
</select> 

lo quiero para que cuando el usuario selecciona 1, esto es lo que el usuario puede elegir para desplegable 2:

<select id="theOptions2"> 
    <option value="a">a</option> 
    <option value="b">b</option> 
    <option value="c">c</option> 
</select> 

O si el usuario selecciona 2:

<select id="theOptions2"> 
    <option value="a">a</option> 
    <option value="b">b</option> 
</select> 

O si el usuario sele cts 3:

<select id="theOptions2"> 
    <option value="b">b</option> 
    <option value="c">c</option> 
</select> 

probé el código publicado aquí: jQuery disable SELECT options based on Radio selected (Need support for all browsers)

Pero no funciona para las selecciones.

Por favor ayuda! ¡Gracias!

ACTUALIZACIÓN: me gusta mucho la respuesta Paolo Bergantino tenía en: jQuery disable SELECT options based on Radio selected (Need support for all browsers)

¿Hay alguna forma de modificar esto para trabajar con selecciona en lugar de botones de radio?

jQuery.fn.filterOn = function(radio, values) { 
    return this.each(function() { 
     var select = this; 
     var options = []; 
     $(select).find('option').each(function() { 
      options.push({value: $(this).val(), text: $(this).text()}); 
     }); 
     $(select).data('options', options); 
     $(radio).click(function() { 
      var options = $(select).empty().data('options'); 
      var haystack = values[$(this).attr('id')]; 
      $.each(options, function(i) { 
       var option = options[i]; 
       if($.inArray(option.value, haystack) !== -1) { 
        $(select).append(
        $('<option>').text(option.text).val(option.value) 
        ); 
       } 
      }); 
     });    
    }); 
}; 

Respuesta

15

esto funciona (probado en Safari 4.0.1, 3.0.13 FF):

$(document).ready(function() { 
    //copy the second select, so we can easily reset it 
    var selectClone = $('#theOptions2').clone(); 
    $('#theOptions1').change(function() { 
     var val = parseInt($(this).val()); 
     //reset the second select on each change 
     $('#theOptions2').html(selectClone.html()) 
     switch(val) { 
      //if 2 is selected remove C 
      case 2 : $('#theOptions2').find('option:contains(c)').remove();break; 
      //if 3 is selected remove A 
      case 3 : $('#theOptions2').find('option:contains(a)').remove();break; 
     } 
    }); 
}); 

Y la hermosa interfaz de usuario:

<select id="theOptions1"> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
</select> 
<br /> 
<select id="theOptions2"> 
    <option value="a">a</option> 
    <option value="b">b</option> 
    <option value="c">c</option> 
</select> 
+0

Lo intentaré ahora mismo. Me gusta cómo mantener la interfaz de usuario bonita – Oscar

+0

Este ejemplo me salvó un día de trabajo. ¡Gracias! –

1

Para el registro usted can NOT remove options en una lista de selección en Internet Explorer.

+1

Creo que se refiere a eliminar en lugar de desactivar. – karim79

+0

Ya lo siento, me refería a eliminar ... – Oscar

+0

¡Oh querido Flying Spaghetti Monster! ¡Es un acortador de URL! – random

9

Puede agregar clases a sus <option> s para registrar cuales ir con cada valor de #theOptions1:

<select id="theOptions2"> 
    <option value="a" class="option-1 option-2">a</option> 
    <option value="b" class="option-1 option-2 option-3">b</option> 
    <option value="c" class="option-1 option-3">c</option> 
</select> 

continuación, haga lo siguiente:

$(function() { 
    var allOptions = $('#theOptions2 option').clone(); 
    $('#theOptions1').change(function() { 
     var val = $(this).val(); 
     $('#theOptions2').html(allOptions.filter('.option-' + val)); 
    }); 
}); 
+0

Me gusta esto mejor. Solo una pequeña corrección - debería ser: $ ('# theOptions2'). Html (... –

+0

Bonita mancha. Modifica el código de presentación, pero en general, muy ampliable. – Kzqai

0

En realidad, con el siguiente código eliminará una opción desplegable muy bien en IE, con tal de que no es la opción seleccionada (no va a funcionar en "un" sin anular esa opción en primer lugar):

var dropDownField = $('#theOptions2'); 
dropDownField.children('option:contains("b")').remove(); 

Sólo ejecuta este para eliminar cualquier opción que desea eliminar en virtud de una sentencia condicional con el primer grupo (theOptions1) - que si se selecciona uno de ellos, ejecutar estas líneas:

var dropDownField = $('#theOptions2'); 
if ($('#theOptions1').val() == "2") { 
    dropDownField.children('option:contains("c")').remove(); 
} 
if ($('#theOptions1').val() == "3") { 
    $("#theOptions2 :selected").removeAttr("selected"); 
    $('#theOptions2').val('b'); 
    dropDownField.children('option:contains("a")').remove(); 
} 

- Tom

0

probar esto. esto definitivamente va a trabajar

 $(document).ready(function() { 
 

 
    var oldValue; 
 
    var oldText; 
 
    var className = '.ddl'; 
 

 
    $(className) 
 
       .focus(function() { 
 
        oldValue = this.value; 
 
        oldText = $(this).find('option:selected').text(); 
 
       }) 
 
       .change(function() { 
 
        var newSelectedValue = $(this).val(); 
 
        if (newSelectedValue != "") { 
 
         $('.ddl').not(this).find('option[value="' + newSelectedValue + '"]').remove(); 
 
        } 
 
        if ($(className).not(this).find('option[value="' + oldValue + '"]').length == 0) { // NOT EXIST 
 
         $(className).not(this).append('<option value=' + oldValue + '>' + oldText + '</option>'); 
 
        } 
 
        $(this).blur(); 
 
       }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 
<form action="/Home/Ex2" method="post"> 
 
    <select class="ddl" id="A1" name="A1"> 
 
     <option value="">Select</option> 
 
     <option value="1">A</option> 
 
     <option value="2">B</option> 
 
     <option value="3">C</option> 
 
     <option value="4">D</option> 
 
    </select> 
 
    <hr /> 
 
    <select class="ddl" id="A2" name="A2"> 
 
     <option value="">Select</option> 
 
     <option value="1">A</option> 
 
     <option value="2">B</option> 
 
     <option value="3">C</option> 
 
     <option value="4">D</option> 
 
    </select> 
 
    <hr /> 
 
    <select class="ddl" id="A3" name="A3"> 
 
     <option value="">Select</option> 
 
     <option value="1">A</option> 
 
     <option value="2">B</option> 
 
     <option value="3">C</option> 
 
     <option value="4">D</option> 
 
    </select> 
 
    <hr /> 
 
    <select class="ddl" id="A4" name="A4"> 
 
     <option value="">Select</option> 
 
     <option value="1">A</option> 
 
     <option value="2">B</option> 
 
     <option value="3">C</option> 
 
     <option value="4">D</option> 
 
    </select> 
 
    <hr /> 
 
    <input type="submit" name="submit" value="Save Data" id="btnSubmit" /> 
 
</form>

Cuestiones relacionadas