Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery and css: hide/show select options with a certain css class

In the html code I have select options like this:

  <option value="1" class="myclass5">Value1</option>

In jQuery:

var cod = $(this).val(); // This is the value of another select: when the value 
$("option[class^=myclass]").hide();
$("option[class^=myclass]").each(function () {
    $("option[class^=myclass" + cod + "]").show();
});

EDIT

I have two select. When I select a value in the first select, the second one must be populated accordingly (I have to prevent an ajax call).

I put all the second select values in a session var, but my problem is in selecting only those ones tied to the first select, so I was trying through css classes.

EDIT2

<select name="firstselect">
   <option value="0" selected="selected">Choose...</option>
   <option value="1">Value1</option>
   <option value="2">Value2</option>
   <option value="3">Value3</option>
</select>

<select name="secondselect">
   <option value="0" selected="selected">Choose...</option>
   <option value="myclass1">Value11</option>
   <option value="myclass1">Value12</option>
   <option value="myclass1">Value13</option>
   <option value="myclass2">Value21</option>
   <option value="myclass2">Value22</option>
   <option value="myclass2">Value23</option>
   <option value="myclass3">Value31</option>
   <option value="myclass3">Value32</option>
   <option value="myclass3">Value33</option>
</select>

EDIT3

For me greenish's solution is good, but there is an issue on IE that I don't succeed in explaining: when I use the back button, the user selected value is "lost", that is, if I log on the console the user selected value, I see its "index" in the new cloned select. In the html source code, there is the whole original select.

EDIT4

I resolved thanks to this post

https://forum.jquery.com/topic/jquery-select-box-selectedindex-problems-in-internet-explorer-ie-on-refresh-and-back-buttons

like image 429
Sefran2 Avatar asked Dec 04 '13 16:12

Sefran2


People also ask

How can I show a hidden div when a select option is selected in jQuery?

To show a hidden div when a select option is selected, you can set the value “style. display” to block.

How can I show and hide elements based on selected option with jQuery?

If you want to hide/show div on dropdown selected, use the jQuery hide() and show(). Before you perform hide or show div on dropdown selection, you need to hide them first using CSS display:none.

How do I remove dynamically selected options in jQuery?

Approach: Select the option from select which needs to remove. Use JQuery remove() method to remove the option from the HTML document.

How do I hide a select field?

The hidden attribute hides the <select> element. You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <select> element is not visible, but it maintains its position on the page.


2 Answers

So when I understand your question correctly, you want to make the options of the second select field dependent of the selected value in the first select field.

I tried this quickly and hiding an option with css does not seem to work cross browser, even the latest version of chrome on mac won't hide the options.

So I came up with the following:

HTML first: I used classes to mark the dependencies. This allows the value attribute in the second select field to be used without restrictions.

Also, only options marked as conditional will be changed, the others won't be affected. This is useful for something like the Default value in this scenario.

<select id="firstSelect">
   <option value="0" selected="selected">Choose...</option>
   <option value="value1">Value1</option>
   <option value="value2">Value2</option>
   <option value="value3">Value3</option>
</select>

<select id="secondSelect">
   <option value="0" selected="selected">Choose...</option>
   <option class="conditional value1" value="subValue1">Value1: Sub1</option>
   <option class="conditional value2" value="subValue2">Value2: Sub1</option>
   <option class="conditional value2" value="subValue3">Value2: Sub2</option>
   <option class="conditional value2" value="subValue4">Value2: Sub3</option>
   <option class="conditional value2" value="subValue5">Value2: Sub4</option>
   <option class="conditional value2" value="subValue6">Value2: Sub5</option>
   <option class="conditional value3" value="subValue7">Value3: Sub1</option>
   <option class="conditional value3" value="subValue8">Value3: Sub2</option>
   <option class="conditional value3" value="subValue9">Value3: Sub3</option>
</select>

And the Javascript: To make this work, I copied the options of the secondSelect field and saved them in a variable. This allows me to actually remove options from the select field while I'm still able to retrieve the options from the copy.

$(function(){
    var conditionalSelect = $("#secondSelect"),
        // Save possible options
        options = conditionalSelect.children(".conditional").clone();

    $("#firstSelect").change(function(){
        var value = $(this).val();
        // Remove all "conditional" options               
        conditionalSelect.children(".conditional").remove();
        // Attach options that needs to be displayed for the selected value.
        options.clone().filter("."+value).appendTo(conditionalSelect);
    }).trigger("change");
});

And here's a fiddle that shows the script in action: http://jsfiddle.net/Kn8Gc/

Note: If you get Data form a database and the user already selected #firstSelect, just use the selected="selected" attribute. #secondSelect will automatically display the correct values. Just try the fiddle above and "preselect" for example value1 instead of 0!


Also here's a "generic" function that can be used easily to make any two select fields dependent on eachother (still using the classes conditional+ source value to make the relation):

// "Generic" function
$.conditionalize = function(sourceSelect, conditionalSelect){
    var options = conditionalSelect.children(".conditional").clone();

    sourceSelect.change(function(){
        var value = $(this).val();                  
        conditionalSelect.children(".conditional").remove();
        options.clone().filter("."+value).appendTo(conditionalSelect);
    }).trigger("change");
}

// Used like this:
$.conditionalize($("#firstSelect"), $("#secondSelect"));

And here it is in action: http://jsfiddle.net/NUxQ9/

like image 106
greenish Avatar answered Oct 04 '22 22:10

greenish


I'm not sure I completely understand your question but what about something like this:

$(document).ready(function(){
    var cod = '';
    $('select[name="firstselect"]').change(function(){
        cod = $(this).val();
        if ( cod > 0 ) {
            $('select[name="secondselect"] option').hide().filter(function(){
               return ( $(this).val().substr(7,1) == cod || $(this).val() == 0 ); 
            }).show();
        }
    });
});

http://jsfiddle.net/wVCcH/1/

Alternatively, the dynamic writing option also exists:

var dataset = [ 
    { set: 1, data: [
        { val: "value11", label: "Value 1 - 1" },
        { val: "value12", label: "Value 1 - 2" },
        { val: "value13", label: "Value 1 - 3" } ]
    },
    { set: 2, data: [
        { val: "value21", label: "Value 2 - 1" },
        { val: "value22", label: "Value 2 - 2" },
        { val: "value23", label: "Value 2 - 3" } ]
    }];

var chooser = "<option value='0' selected='selected'>Choose...</option>";

$('select[name="firstselect"]').change(function(){
    var n = $(this).val();                            //get value of data set
    if ( n != 0 ) {
       var str = chooser; n--;                        //0-based n
       for (i=0; i<dataset[n].data.length; i++) {     //write options
          str += "<option value='" + dataset[n].data[i].val + "'>" + dataset[n].data[i].label + "</option>"
        }
        $('select[name="secondselect"]').html(str).attr("disabled",false);
    }
});

http://jsfiddle.net/UNy9Z/4/

like image 40
greener Avatar answered Oct 04 '22 23:10

greener