41

here is my html.

<select id="type">
<option value="item1">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
</select>

<select id="size">
<option value="">-- select one -- </option>
</select>

here is the jquery i tried but was unsuccessful.

$(document).ready(function() {

if( $("#type").val("item1"))
{
  $("#size").html("<option value='test'>test</option><option value="test2">test2</option>);
}
elseif( $("#type").val("item2"))
{
   $("#size").html("<option value='anothertest1'>anothertest1</option>");
}

});

basically what i'm trying to do is if an option is selected in #type then the size select is populated with options associated to it. how can i do this?

thanks

sarmenhbbi
  • 413
  • 1
  • 4
  • 4

9 Answers9

61

Here is an example of what you are trying to do => fiddle

$(document).ready(function () {
    $("#type").change(function () {
        var val = $(this).val();
        if (val == "item1") {
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");
        } else if (val == "item2") {
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");
        } else if (val == "item3") {
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");
        } else if (val == "item0") {
            $("#size").html("<option value=''>--select one--</option>");
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="type">
    <option value="item0">--Select an Item--</option>
    <option value="item1">item1</option>
    <option value="item2">item2</option>
    <option value="item3">item3</option>
</select>

<select id="size">
    <option value="">-- select one -- </option>
</select>
Qrazier
  • 162
  • 4
  • 15
rcravens
  • 8,320
  • 2
  • 33
  • 26
  • 5
    Here is even a cleaner example. In this case, the content is refactored into a JavaScript array. This simplifies the 'change' logic tremendously. Easier to maintain. http://jsfiddle.net/YPsqQ/1/ – rcravens Dec 18 '10 at 23:18
  • thanks thats exactly what i needed. i wasn't too sure to try the == next time ill try thanks. – sarmenhbbi Dec 18 '10 at 23:19
  • greaaaaaat answer !, now i want to try the to change layout. – Bhimbim Sep 12 '13 at 07:41
  • 2
    Only problem with this example (as is) is that it doesn't set the value for initial state (of item1). You need to change it to one value then back to item1 . – Sir Geek May 08 '17 at 16:55
  • how we can set the selected value of two select box? for example i set item3 for selector 1 and item3: test2 for selector 2 but if i refresh page it not correct. – Ali Qorbani Nov 29 '17 at 08:56
  • I was about to add the same comment as Sir Geek. Is there a way of initializing this so we can have an initial state, including a populated second select element? – Doug Lerner Mar 24 '19 at 11:52
  • It is never beneficial to repeat an option's text as its `value` attribute. When the two values are identical, you can safely remove the unneeded HTML markup bloat by omitting the `value` declaration. Javascript and form submissions will still behave in the same fashion. This answer is missing its plain English explanation. – mickmackusa Apr 28 '23 at 02:02
14

you can use data-tag in html5 and do this using this code:

<script>
 $('#mainCat').on('change', function() {
  var selected = $(this).val();
  $("#expertCat option").each(function(item){
   console.log(selected) ;  
   var element =  $(this) ; 
   console.log(element.data("tag")) ; 
   if (element.data("tag") != selected){
    element.hide() ; 
   }else{
    element.show();
   }
  }) ; 
  
  $("#expertCat").val($("#expertCat option:visible:first").val());
  
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<select id="mainCat">
   <option value = '1'>navid</option>
   <option value = '2'>javad</option>
   <option value = '3'>mamal</option>
  </select>
  
  <select id="expertCat">
   <option  value = '1' data-tag='2'>UI</option>
   <option  value = '2' data-tag='2'>Java Android</option>
   <option  value = '3' data-tag='1'>Web</option>
   <option  value = '3' data-tag='1'>Server</option>
   <option  value = '3' data-tag='3'>Back End</option>
   <option  value = '3' data-tag='3'>.net</option>
  </select>
Navid_pdp11
  • 3,487
  • 3
  • 37
  • 65
  • 1
    This looks like the way to go, and if it's correct I'll give you an upvote, but FYI the code snippet does not work. – Erica Kane Jun 13 '16 at 18:36
  • 1
    it works but in first run combo box onchange event not raise if you change value of first combo box this work fine.... this was a sample for changing value by selecting ..... for real world you most refactor this code to work like a charm :) – Navid_pdp11 Jun 14 '16 at 16:37
4

Here is my simple solution using Jquery filters.

$('#publisher').on('change', function(e) {
   let selector = $(this).val();
   $("#site > option").hide();
   $("#site > option").filter(function(){return $(this).data('pub') == selector}).show();
});

JSFIDDLE

pramod
  • 2,258
  • 1
  • 17
  • 22
  • Note this does not work in IE-- display:none does not hide the option in IE. I used your answer but had to add a few more lines to get it to work in IE https://stackoverflow.com/questions/20373558/options-with-displaynone-not-hidden-in-ie – Brett Mar 04 '20 at 23:02
2

You can use switch case like this:

$(document).ready(function () {
  $("#type").change(function () {
     switch($(this).val()) {
        case 'item1':
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");
            break;
        case 'item2':
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");
            break;
        case 'item3':
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");
            break;
        default:
            $("#size").html("<option value=''>--select one--</option>");
     }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="type">
    <option value="item0">--Select an Item--</option>
    <option value="item1">item1</option>
    <option value="item2">item2</option>
    <option value="item3">item3</option>
</select>

<select id="size">
    <option value="">-- select one -- </option>
</select>
Rashid
  • 272
  • 2
  • 6
1

as a complementary answer to @Navid_pdp11, which will enable to select the first visible item and work on document load as well. put the following below your body tag

<script>
$('#mainCat').on('change', function() {
    let selected = $(this).val();
    $("#expertCat option").each(function(){
        let element =  $(this) ;
        if (element.data("tag") != selected){
            element.removeClass('visible');
            element.addClass('hidden');
            element.hide() ;
        }else{
            element.removeClass('hidden');
            element.addClass('visible');
            element.show();
        }
    });
    let expertCat = $('#expertCat');
    expertCat.prop('selectedIndex',expertCat.find("option.visible:eq(0)").index());
}).triggerHandler('change');
</script>
Pomanh
  • 640
  • 9
  • 14
0

Your if statement is setting the value. You want to compare it by doing this

if ($("#type").val() == "item1") {
 ...
}

daLizard is right though. You want an event handler. document.ready runs only once, when the page DOM is ready to be used.

Vadim
  • 17,897
  • 4
  • 38
  • 62
0

I don't quote understand what you are trying to achieve, but you need an event listener. Something like:

$('#type').change(function() {
   alert('Value changed to ' + $(this).attr('value'));
});

This will give you the value of the selected option tag.

daLizard
  • 430
  • 4
  • 14
0
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form name="index">
<select name="in" onchange="myFunction()">
<option>Select One</option>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<select id="select">
<option>Select One</option>
</select>
</form>
</body>
</html>
<script>
function myFunction(){
var x=document.index.in.value;
if(x=="One"){
document.getElementById('select').innerHTML="<option>A</option><option>Two</option>";
}
}
</script>
Tamim
  • 11
  • 2
0

function showDiv(prefix, chooser) {
  var selectedOption = (chooser.options[chooser.selectedIndex].value);
  if (selectedOption == "2") {
    var div = document.getElementById(prefix + "2");
    div.style.display = 'block';
  } else {
    var div = document.getElementById(prefix + "2");
    div.style.display = 'None';
  }
}
<div class="form-label-group">
  <select name="name" id="cboOptions" onchange="showDiv('div',this)" class="form-control">
    <option value="">How can we help you?</option>
    <option value="2">Support</option>
    <option value="1">Feedback</option>
  </select>
  <div id="div2" style="display:none;">
    <select id="type">
      <option value="item0">--Select--</option>
      <option value="item1">Technical</option>
      <option value="item2">Non-Technical</option>
    </select>
  </div>

</div>
sachin vinay
  • 1
  • 1
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 29 '21 at 08:52