Show a Second Dropdown Based on Previous Dropdown Selection

Show a second dropdown based on previous dropdown selection

One way or another, you've already ended up with what's probably the easiest HTML markup to use for the job:

<select size="1" id="Rank" title="" name="Rank">
<option value="">-Select Your Rank-</option>
<option value="Airman">Airman</option>
<option value="Airman First Class">Airman First Class</option>
<option value="Senior Airman">Senior Airman</option>
<option value="Staff Sergeant">Staff Sergeant</option>
<option value="Senior Master Sergeant">Senior Master Sergeant</option>
</select>

and then one <element> container for each possibility of <option>.

<div>
// For Airman
</div>
<div>
// For Senior Airman
</div>

... etc etc...

I'd use this same layout for everything that depends on which <option> is selected; the unique-line-of-text you want, the other-select-box, etc etc. I'd wrap each one in a container element, so you can easily target all the elements as one.

<div class="container">
<div>
Line of text for Airman
</div>
<div>
Line of text for Senior Airman
</div>
</div>

<div class="container">
<div>
<select>
<option>Airman Stuff</option>
</select>
</div>
<div>
<select>
<option>Senior Airman Stuff</option>
</select>
</div>
</div>

Now whack a identifier to each of the <div>'s we've got, so when the "Airman" is selected, we know which <div>'s are the Airmans (so we know to show those ones!)

<div class="container">
<div class="airman">
Line of text for Airman
</div>
<div class="senior-airman">
Line of text for Senior Airman
</div>
</div>

<div class="container">
<div class="airman">
<select>
<option>Airman Stuff</option>
</select>
</div>
<div class="senior-airman">
<select>
<option>Senior Airman Stuff</option>
</select>
</div>
</div>

And add the same identifier to the <options>'s of the <select id="rank">:

<select size="1" id="Rank" title="" name="Rank">
<option value="">-Select Your Rank-</option>
<option value="airman">Airman</option>
<option value="senior-airman">Senior Airman</option>
</select>

Now we've got this markup, applying the JavaScript for the hiding/showing is so easy!

$(document).ready(function () {
$('#Rank').bind('change', function () {
var elements = $('div.container').children().hide(); // hide all the elements
var value = $(this).val();

if (value.length) { // if somethings' selected
elements.filter('.' + value).show(); // show the ones we want
}
}).trigger('change'); // Setup the initial states
});

Done; checkout an example: http://jsfiddle.net/3UWk2/1/

An update for your comment

The reason your attempt to change the code like you did didn't work is because we've currently got no event handler bound to the 2nd level <select> boxes; only to <select id="rank">

You need to basically repeat everything we've just done for the first level nav, for the second level nav. Instead of using an #id selector for the <select>, use a .class; because we've got more than one <select> element to target, and #id's have to be unique:

$('.second-level-select').bind('change', function () {
var elements = $('div.second-level-container').children().hide(); // hide all the elements
var value = $(this).val();

if (value.length) { // if somethings' selected
elements.filter('.' + value).show(); // show the ones we want
}
}).trigger('change'); // Setup the initial states

We've also had to change the name of the div.container, to stop the <select> boxes hiding each others elements.

Check out an updated example here: http://jsfiddle.net/3UWk2/3/

Show second dropdown options based on first dropdown selection jquery

I don't see where the problem is just drop the part that correspond to the all stuff and you are done.

Take a look: JSnippet Demo

jQuery:

$(function(){
$('#groups').on('change', function(){
var val = $(this).val();
var sub = $('#sub_groups');
$('option', sub).filter(function(){
if (
$(this).attr('data-group') === val
|| $(this).attr('data-group') === 'SHOW'
) {
$(this).show();
} else {
$(this).hide();
}
});
});
$('#groups').trigger('change');
});

HTML:

<select id="groups">
<option value='America'>America</option>
<option value='Europe'>Europe</option>
<option value='Asia'>Asia</option>
<select>

<select id="sub_groups">
<option data-group='SHOW' value='0'>-- Select --</option>
<option data-group='America' value='Argentina'>Argentina</option>
<option data-group='America' value='Brazil'>Brazil</option>
<option data-group='America' value='Chile'>Chile</option>
<option data-group='Europe' value='Italy'>Italy</option>
<option data-group='Europe' value='France'>France</option>
<option data-group='Europe' value='Spain'>Spain</option>
<option data-group='Asia' value='China'>China</option>
<option data-group='Asia' value='Japan'>Japan</option>
<select>

EDIT
As mentioned in the comments this method is not supported by safari. here is a second solution that should work on any modern browser:

JSnippet DEMO

jQuery:

    $(function(){
$('#groups').on('change', function(){
var val = $(this).val();
var sub = $('#sub_groups');
$('option', sub).filter(function(){
if (
$(this).attr('data-group') === val
|| $(this).attr('data-group') === 'SHOW'
) {
if ($(this).parent('span').length) {
$(this).unwrap();
}
} else {
if (!$(this).parent('span').length) {
$(this).wrap( "<span>" ).parent().hide();
}
}
});
});
$('#groups').trigger('change');
});

Display second dropdown based on selection in first dropdown?

I just write a small jQuery code, I hope it'll help you out. Thanks

$(document).ready(function() {  $('#type_w').change(function() {    $(".hide-submenu").hide();    $("#w_" + this.value).show();  });});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><select id="type_w">  <option value="null" selected> --- </option>  <option value="lmg"> LMG </option>  <option value="marks"> Marksman Rifle </option></select>
<select id="w_lmg" class="hide-submenu" hidden> <option value="null" selected> --- </option> <option value="mg5"> MG5 </option></select>
<select id="w_marks" class="hide-submenu" hidden> <option value="null" selected> --- </option> <option value="mk17"> MK17 Military </option></select>

how to populate dropdown list based on previous dropdown selected value

You can use change event on your select-box . Inside this get value of selected option using $(this).val() this will return you array so use for-loop to iterate through value and show options where value matches in second dropdown . Lastly refresh your selectpicker to update changes .

Demo Code :

$('#id1').on('change', function(e) {
var values = $(this).val()
$("#id2 option").hide() //hide all options
$('#id2').selectpicker('deselectAll') //if want to remove all selcted optn
if (values.length > 0) {
for (var i = 0; i < values.length; i++) {
//show where value is same..
$("#id2 option[value=" + values[i] + "]").show()
}
} else {
$("#id2 option").show() //show all options
}
$('#id2').selectpicker('refresh'); //refresh selctpicker
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>
<select id="id1" name="name1" class="selectpicker" data-style="form-control" data-live-search="true" title="Select Fruits" multiple="multiple">
<option value="Fruit">Fruits</option>
<option value="Animal">Animal</option>
</select>
<select id="id2" name="name2" class="selectpicker" data-style="form-control" data-live-search="true" title="Select Product" multiple="multiple">
<option value="Fruit">Mangoes</option>
<option value="Fruit">Apple</option>
<option value="Animal">Dog</option>
<option value="Animal">Cat </option>

</select>

Select another dropdown value based on the previous dropdown selection

You can use javascript like this:

function Checker(el){

const select = document.getElementById('counter');
removeOptions(select);
if(el.value == '4'){
var option1 = document.createElement("option");
option1.text = "Driveway";
option1.value = "2";
select.add(option1);
}else{
var option2 = document.createElement("option");
option2.text = "Table Service";
option2.value = "1";
select.add(option2);
var option1 = document.createElement("option");
option1.text = "Driveway";
option1.value = "2";
select.add(option1);

}
}

function removeOptions(selectElement) {
var i, L = selectElement.options.length - 1;
for (i = L; i >= 0; i--) {
selectElement.remove(i);
}
}
<div class="form-group col-md-12">
<select name="service_type" id="service_type" class="form-control form-control-line" onChange="Checker(this)" required>
<option value="" selected="selected" >Select Service</option>
<option value="1">Dining</option>
<option value="2">Beverages</option>
<option value="3">Liquor</option>
<option value="4">Takeout</option>
</select>
</div>

<div class="form-group col-md-12">
<select name="counter" id="counter" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Service Fist</option>

</select>
</div>

Dynamically update a dropdown list based on another dropdown list?

You can use split(',') to split values then using for-loop you can get values from split array and finally use $("#beta option[value=" + vals + "]").show() to show options where values matches.

Demo Code:

$("#alpha").on("change", function() {
var values = $(this).val().split(',') //split value which is selected
$("#beta option").hide() //hide all options from slect box
//loop through values
for (var i = 0; i < values.length; i++) {
var vals = values[i]
$("#beta option[value=" + vals + "]").show()//show that option

}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<select class="browser-default" id="alpha">
<option value="a,b,c">One</option>
<option value="d">Two</option>
<option value="e,f">Three</option>
</select>

<select class="browser-default" id="beta">
<option selected="selected" value="">--select one-- </option>
<option value="a">First</option>
<option value="b">Second</option>
<option value="c">Third</option>
<option value="d">Fourth</option>
<option value="e">Fifth</option>
<option value="f">Sixth</option>
</select>

Updating dropdown based on previous dropdown selection

this would work with any number of dropdown.

you can generate random attributes to test.

$(document).ready(function () {    /* generates random attributes */    var div_attributes = $('#div_attributes');    var select_colors = $('#select_colors');    var select_sizes = $('#select_sizes');    var select_attr0 = $('#select_attr0');    var select_attr1 = $('#select_attr1');
$('#btnGenerate').on('click', function () { var result = "";
// var index = getRandomArbitrary(1, select_sizes.find('option').get().length); var random_attribute = select_sizes.find('option').eq(index).attr('value'); result += random_attribute;
// index = getRandomArbitrary(1, select_colors.find('option').get().length); random_attribute = select_colors.find('option').eq(index).attr('value'); result += '_' + random_attribute;
// index = getRandomArbitrary(1, select_attr0.find('option').get().length); random_attribute = select_attr0.find('option').eq(index).attr('value'); result += '_' + random_attribute;
// index = getRandomArbitrary(1, select_attr1.find('option').get().length); random_attribute = select_attr1.find('option').eq(index).attr('value'); result += '_' + random_attribute;
$('<div>' + result + '</div>').appendTo(div_attributes);
div_attributes.find('div').each(function () { var item = $(this); attributes.push(item.text()); }); SetFirstSelect(); });
var attributes = []; //sets first select SetFirstSelect(); function SetFirstSelect() { $.each(attributes, function (i, val) { var attribute = val.split('_')[0]; $('.attribute_price').eq(0).find('option[value="' + attribute + '"]').show(); }); } //control attributes array var selected_val = []; $('.attribute_price').on('change', function () { var item = $(this); var index = item.index('.attribute_price'); selected_val[index] = item.val(); var select = $('.attribute_price').eq(index + 1); var selected_attribute = item.val(); for (var i = index + 1; i < $('.attribute_price').get().length; i++) { $('.attribute_price').eq(i).find('option').hide(); $('.attribute_price').eq(i).prop('selectedIndex', 0) } var selected_val_str = selected_val[0]; for (var i = 1; i <= index; i++) { selected_val_str += '_' + selected_val[i]; } $.each(attributes, function (j, val) { if (val.indexOf(selected_val_str) >= 0) { var attribute1 = val.split('_')[index + 1];
select.find('option[value="' + attribute1 + '"]').show(); } }); });
function getRandomArbitrary(min, max) { return Math.floor(Math.random() * (max - min) + min); }});
.attribute_price option {            display: none;        }                .container {        margin:30px;        }                .row > div {        padding:10px;        }        .btn {        margin-top:20px;        }
<script  src="https://code.jquery.com/jquery-3.3.1.min.js"  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="  crossorigin="anonymous"></script>  <!-- Latest compiled and minified CSS --><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme --><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript --><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <div class="container"> <div class="row"> <div style="width:50%; float:left"> <input type="button" class="btn btn-primary" id="btnGenerate" value="generate random attributes" /> <div id="div_attributes"></div> </div> <div style="width:50%; float:left"> <div class="form-group"> <label>Sizes</label> <select class="form-control attribute_price" id="select_sizes"> <option value="">select size</option> <option value="small">small</option> <option value="large">large</option> <option value="medium">medium</option> </select> </div> <div class="form-group"> <label>color</label> <select id="select_colors" class="form-control attribute_price"> <option value="">select color</option> <option value="black">black</option> <option value="yellow">yellow</option> <option value="red">red</option> </select> </div> <div class="form-group"> <label>attrType0</label> <select id="select_attr0" class="form-control attribute_price"> <option value="">select attr0</option> <option value="attr00">attr00</option> <option value="attr01">attr01</option> <option value="attr02">attr02</option> </select> </div> <div class="form-group"> <label>attrType1</label> <select id="select_attr1" class="form-control attribute_price"> <option value="">select attr1</option> <option value="attr10">attr10</option> <option value="attr11">attr11</option> <option value="attr12">attr12</option> </select> </div> </div>
</div> </div>

How to show a second dropdown based on previous dropdown value using Javascript

First of all, you have a duplicate id value in your HTML. I assume the div should not have bir but biro as id attribute value.

You could then add a data-dept to the option elements that you add dynamically to the second drop down, and give it the value of the deptId:

foreach ($birs as $rl)
{
?>
<option value="<?php echo $rl->birId ?>"
data-dept="<?php echo $rl->deptId ?>" >
<?php echo $rl->birName ?></option>
<?php
}

Then in the script, read out that value with dataset.dept (make sure you have corrected the div's id attribute in the HTML).

Here is a snippet (without PHP):

function checkvalue(val) {     if (+val) {         for (var option of bir.options) {            if (option.dataset.dept) { // don't touch first entry                option.style.display = option.dataset.dept == val ? '' : 'none';            }        }    }    bir.value = 0; // reset selection    biro.style.display = +val ? '' : 'none'; // show/hide }
function checkvalues(val) {}
<div class="col-md-6">    <div class="form-group">        <label for="Dept">Dept</label>        <select class="form-control required" id="Dept" name="Dept" onchange='checkvalue(this.value)'>            <option value="0">Dept</option>            <option value="2">2</option>            <option value="5">5</option>        </select>    </div></div>  <div class="col-md-6" >    <div class="form-group" id="biro" style='display:none'>        <label for="bir">Bir</label>        <select class="form-control required" id="bir" name="bir" onchange='checkvalues(this.value)'>            <option value="0">Pilih Bir</option>            <option value="9" data-dept="2">bir for 2</option>            <option value="10" data-dept="5">bir for 5</option>            <option value="8" data-dept="2">another bir for 2</option>            <option value="15" data-dept="5">another bir for 5</option>        </select>    </div></div>  


Related Topics



Leave a reply



Submit