Hiding select list option values while using jQuery Chosen - javascript

I have created a simple app containing <select> lists which hide() or show() option values based on previous selections.
There are two lists, one with vehicle Makes and the other with vehicle Models. When a certain Make is selected, i.e. BMW, the next Make <select> appears only showing BMW models. And vice versa with Audi and so on.
Within the Models list, I have attached an ID to every <option> value and show or hide those <option> values based on previous selections. For example if BMW is selected, it will hide the two Audi model <option>'s, Q1 and Q3. If Audi is selected, it will hide the two BMW model <option>'s, X1 and X2.
I was successful in achieving this basic functionality; however, when I integrated jQuery's Chosen, it no longer worked. I really like Chosen and once I build out this app it will be very useful, so I would love to achieve the same functionality with it integrated.
Here is the simple code file:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css">
<style type="text/css">
.chosen-select {width:200px}
.hidden {display: none;}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".chosen-select").chosen({
disable_search_threshold: 4
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
var $models = $('#s2');
var $drivetrain = $('#s3');
var $bmwmodels = $('#X1, #X2');
var $audimodels = $('#Q1, #Q3');
$('#s1').change(function() {
var selectedValue = $(this).val();
if(selectedValue == 'BMW') {
$audimodels.hide();
$drivetrain.parent().hide();
$models.parent().show();
$bmwmodels.show();
}
else if (selectedValue == 'AUDI') {
$bmwmodels.hide();
$drivetrain.parent().hide();
$models.parent().show();
$audimodels.show();
}
else {
$bmwmodels.hide();
$audimodels.hide();
$models.parent().hide();
$drivetrain.parent().hide();
}
});
//Hide onload
function hide() {
$models.parent().hide();
$drivetrain.parent().hide();
$bmwmodels.hide();
$audimodels.hide();
}
// call hide AFTER .chosen() has been invoked on the visible elements
hide();
});
</script>
</head>
<body onload="hide()">
<table>
<tr>
<td>
<select data-placeholder="Select Brand" class="chosen-select" id="s1">
<option disabled selected></option>
<option value="BMW">BMW</option>
<option value="AUDI">AUDI</option>
<option value="nothing" id="nothing">Nothing</option>
</select>
</td>
</tr>
<tr>
<td>
<select data-placeholder="Select Model" class="chosen-select" id="s2">
<option disabled selected></option>
<option value="nothing" id="nothing">Nothing</option>
<option value="X1" id="X1">X1</option>
<option value="X2" id="X2">X2</option>
<option value="Q1" id="Q1">Q1</option>
<option value="Q3" id="Q3">Q3</option>
</select>
</td>
</tr>
</table>
</body>
</html>
Any help would be greatly appreciated! Thanks so much.

$(".chosen-select").trigger('chosen:updated'); You need to notify Chosen that your options have updated. This code updated Chosen to take care of updated options.
One thing to note however that it dont work to remove pre-select, you need to find solution within Chosen on how to remove pre-selection.
$(document).ready(function() {
var $models = $('#s2');
var $drivetrain = $('#s3');
var $bmwmodels = $('#X1, #X2');
var $audimodels = $('#Q1, #Q3');
console.log( $bmwmodels, $audimodels);
$('#s1').change(function() {
var selectedValue = $(this).val();
if (selectedValue == 'BMW') {
$audimodels.hide();
$drivetrain.parent().hide();
$models.parent().show();
$bmwmodels.show();
} else if (selectedValue == 'AUDI') {
$bmwmodels.hide();
$drivetrain.parent().hide();
$models.parent().show();
$audimodels.show();
} else {
$bmwmodels.hide();
$audimodels.hide();
$models.parent().hide();
$drivetrain.parent().hide();
}
$(".chosen-select").trigger('chosen:updated');
});
//Hide onload
function hide() {
$models.parent().hide();
$drivetrain.parent().hide();
$bmwmodels.hide();
$audimodels.hide();
}
// call hide AFTER .chosen() has been invoked on the visible elements
$(".chosen-select").chosen({
disable_search_threshold: 4
});
hide();
});
.chosen-select {
width: 200px
}
.hidden {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
</head>
<body>
<table>
<tr>
<td>
<select data-placeholder="Select Brand" class="chosen-select" id="s1">
<option disabled selected></option>
<option value="BMW">BMW</option>
<option value="AUDI">AUDI</option>
<option value="nothing" id="nothing">Nothing</option>
</select>
</td>
</tr>
<tr>
<td>
<select data-placeholder="Select Model" class="chosen-select" id="s2">
<option disabled selected></option>
<option value="nothing" id="nothing">Nothing</option>
<option value="X1" id="X1">X1</option>
<option value="X2" id="X2">X2</option>
<option value="Q1" id="Q1">Q1</option>
<option value="Q3" id="Q3">Q3</option>
</select>
</td>
</tr>
</table>
</body>
</html>

Related

javascript shows all associated DIVs on a dropdown box select

I am new to javascript and must have looked at almost all of the previous questions here and elsewhere related to this question and none seem to do the trick because they use asp, php, Ajax etc.
I use jQuery code for several other items on the page and have found that their css can cause issues with my pages and am not keen on using it either.
In my case, is there a way to select a country from a drop down box and then display a dropdown box with the states or provinces for that country. My code is shown below but when I run it, it shows all DIVs and not just the DIV that applies to the country selected. If a country has no states/province it will display nothing but passes a value of 0.
I'd like to know what is wrong with this code.
Second question is, the page starts with a default country and its states/provinces but since I use onChange on the country select, the javascript would not be triggered because initially there is no change. Regardless, even when I do change the country from its default, all DIVs are displayed anyway.
Is it possible to show the states/provinces for the default country and still use javascript for any change made to the default selection. It does not show this in the sample below, but the values for the countries and the associated states/provinces come from a database and can therefore not be incorporated in the javascript.
Any help or suggestions will be greatly appreciated.
<TABLE>
<TR><TD>Country</DIV></TD>
<TD><SELECT NAME="countryid" onChange="showstate(this.options[this.selectedIndex].value)">
<OPTION VALUE="NONE">Select a country</OPTION>
<OPTION VALUE="CA" SELECTED>Canada</OPTION>
<OPTION VALUE="US">United States</OPTION>
<OPTION VALUE="ES">Spain</OPTION>
</SELECT></TD>
</TR>
<script>
function showstate(country) {
if (country == "CA") {
hiddenDivUS.style.display='none';
hiddenDivNONE.style.display='none';
hiddenDivCA.style.display='block';
}
else {
if (country == "US") {
hiddenDivCA.style.display='none';
hiddenDivNONE.style.display='none';
hiddenDivUS.style.display='block';
}
else {
hiddenDivCA.style.display='none';
hiddenDivUS.style.display='none';
hiddenDivNONE.style.display='block';
}
}
</script>
<DIV ID="hiddenDivNONE" STYLE="display:none">
<TR><TD><DIV CLASS="inputlabel">Prov/State</DIV></TD>
<TD><INPUT TYPE="hidden" NAME="provid" VALUE="0"></TD>
</TR>
</DIV>
<DIV ID="hiddenDivCA" STYLE="display:none">
<TR><TD><DIV CLASS="inputlabel">Prov/State</DIV></TD>
<TD><SELECT NAME="provid">
<OPTION VALUE="101">British Columbia</OPTION>
.......
<OPTION VALUE="165">Yukon Territories</OPTION>
</SELECT></TD>
</TR>
</DIV>
<DIV ID="hiddenDivUS" STYLE="display:none">
<TR><TD><DIV CLASS="inputlabel">Prov/State</DIV></TD>
<TD><SELECT NAME="provid">
<OPTION VALUE="201">Alaska</OPTION>
.......
<OPTION VALUE="265">Wyoming</OPTION>
</SELECT></TD>
</TR>
</DIV>
</TABLE>
Instead of listing the proper DIV it shows all three of them
First off, careful with your capitals.
Secondly try to keep all js at the bottom of the page.
This code is using ES6 so you might wanna check if it will work in all browsers but you can see whats going on.
el.classList is supported by most browsers however add,remove and toggle are not (were not.. not sure now)
I have used some regex to grab all elements using the id state_ so we can hide them, then we target the exact one to make it visible, you can probably clean that up also.
<style>
.hidden {
display: none;
}
</style>
<select name="countryid" onChange="showState(event)">
<option value="">Select a country</option>
<option value="ca">Canada</option>
<option value="us">United States</option>
<option value="es">Spain</option>
</select>
<div id="state_ca" class="hidden">
This is hidden unless Canada is selected.
</div>
<div id="state_us" class="hidden">
This is hidden unless America is selected.
</div>
<script>
function showState(event) {
const countryCode = event.target.value;
const states = document.querySelectorAll('[id^=state_]');
const el = document.getElementById(`state_${countryCode}`);
states.forEach(el => {
if (el.classList.contains('hidden')) {
return;
}
el.classList.add('hidden');
});
if (el) {
el.classList.remove('hidden');
}
}
</script>
according to me this can be the answer to your problem. You can make a few changes in the code which I have not done.
function addStates() {
var selectCountry = document.getElementById("selectCountry").value;
console.log(selectCountry);
var selectState = document.getElementById("selectState");
if (selectCountry == "india") {
var option1 = document.createElement("option");
option1.value = "punjab";
option1.text = "Punjab";
selectState.add(option1);
var option2 = document.createElement("option");
option2.value = "karnataka";
option2.text = "Karnataka";
selectState.add(option2);
} else if (selectCountry == "usa") {
var option1 = document.createElement("option");
option1.value = "florida";
option1.text = "Florida";
selectState.add(option1);
var option2 = document.createElement("option");
option2.value = "california";
option2.text = "California";
selectState.add(option2);
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<div>
<span>Select a country: </span>
</div>
<div>
<select onchange="addStates()" id="selectCountry">
<option value="" selected disabled>Please select a country</option>
<option value="india">India</option>
<option value="usa">USA</option>
</select>
</div>
</div>
<div>
<div>
<span>Please select a state: </span>
</div>
<div>
<select id="selectState">
</select>
</div>
</div>
</body>
</html>
I figured out how to get the desired result (see code below)
<!DOCTYPE HTML>
<HTML>
<HEAD>
<script>
function showStates(country)
{
if (country == "101")
{ document.getElementById('CAprov').style.display='block';
document.getElementById('Default').style.display='none';
document.getElementById('USstate').style.display='none';
document.getElementById('NoProv').style.display='none';
}
else if (country == "102")
{ document.getElementById('CAprov').style.display='none';
document.getElementById('Default').style.display='none';
document.getElementById('USstate').style.display='block';
document.getElementById('NoProv').style.display='none';
}
else
{ document.getElementById('CAprov').style.display='none';
document.getElementById('USstate').style.display='none';
document.getElementById('Default').style.display='none';
document.getElementById('NoProv').style.display='block';
}
return false;
}
</script>
</HEAD>
<BODY TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0" BORDER="0">
<FORM METHOD="post">
<TABLE>
<TR><TD>Country</TD>
<TD><SELECT NAME="country" id="country" onChange="showStates(this.options[this.selectedIndex].value);">
<OPTION VALUE="101" SELECTED>Canada</OPTION>
<OPTION VALUE="102">United States</OPTION>
<OPTION VALUE="314">Germany</OPTION>
</SELECT></TD></TR>
<TR ID="Default" STYLE="display: block;"><TD>Province</TD>
<TD><SELECT NAME="provid">
<OPTION VALUE="0">Select province</OPTION>
<OPTION VALUE="139">Newfoundland/Labrador</OPTION>
<OPTION VALUE="143">Nova Scotia</OPTION>
<OPTION VALUE="134">New Brunswick</OPTION>
<OPTION VALUE="149">Prince Edward Island</OPTION>
</SELECT></TD></TR>
<TR ID="CAprov" STYLE="display: none;"><TD>Province</TD>
<TD><SELECT NAME="provid">
<OPTION VALUE="0">Select province</OPTION>
<OPTION VALUE="139">Newfoundland/Labrador</OPTION>
<OPTION VALUE="143">Nova Scotia</OPTION>
<OPTION VALUE="134">New Brunswick</OPTION>
<OPTION VALUE="149">Prince Edward Island</OPTION>
</SELECT></TD></TR>
<TR ID="USstate" STYLE="display: none;"><TD>State</TD>
<TD><SELECT NAME="provid">
<OPTION VALUE="0">Select state</OPTION>
<OPTION VALUE="102">Alabama</OPTION>
<OPTION VALUE="105">Arizona</OPTION>
<OPTION VALUE="106">Arkansas</OPTION>
<OPTION VALUE="108">California</OPTION>
</SELECT></TD></TR>
<TR ID="NoProv" STYLE="display: none;"><TD>Prov/State</TD>
<TD><INPUT TYPE="hidden" NAME="provid" VALUE="0"> </TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>

Get option value in multiple select tag using jquery

<?php for($i = 1; $i <=5; $i++ ){?>
<tr id="row">
<td class="input-field col s2">
<label>Week Days</label>
<select id="week_days<?php echo $i;?>" data-rel="chosen" name="week_days<?php echo $i;?>[]" class="form-control" multiple="multiple">
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
</select>
</td>
</tr>
<?php } ?>
<a id="more_btn" class="right" href="javascript:void(0);"><img src="../../assets/images/icons/add-icon.ico" width="23px" title="Add More"/></a>
How to get the value of option using jquery?
issue is that I am getting a null on click anchor tag. Waht is the right way to getting option value. First user select a Monday option and click on add more anchor tag then in alert show 1 value that is correct but when user change a option and click on add more anchor tag then alert show it null. why it show null instead of 1,2,3,4,5?
<script type="text/javascript">
var j=1;
$('#more_btn').click(function() {
j++;
var u = j-1;
var prev_weekdays = $('#week_days'+u).val();
alert(prev_weekdays);
});
</script>
When the more_btn link click get the selected value of weekdays and alert it see the example
Ex -
<script type="text/javascript">
$('#more_btn').click(function() {
var prev_weekdays = $('#week_days').find(":selected").text();
alert(prev_weekdays);
});
</script>
make the your select as
<select id="week_days" data-rel="chosen" class="form-control" multiple="multiple">
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
</select>
Tell me if this is Working or not
Hope this will resolve your issue
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Values from Multiple Select Box</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function(){
var countries = [];
$.each($(".country option:selected"), function(){
countries.push($(this).val());
});
alert("You have selected the country - " + countries.join(", "));
});
});
</script>
</head>
<body>
<p>Press control key (Ctrl) to select multiple values:</p>
<form>
<label>Country:</label>
<select class="country" multiple="multiple" size="5">
<option value="1">United States</option>
<option value="2">India</option>
<option value="3">United Kingdom</option>
<option value="4">Brazil</option>
<option value="5">Germany</option>
</select>
<button type="button">Get Values</button>
</form>
</body>
</html>

Display image with select list APEX

I have two items: a Select List and a Display Image. The Select List has three values for the user to choose from. If the user selects on of the values then the Image View will show a related image with the selected value and if the selected value of the Select List will switch also change the picture.
I tried putting the script in the section: JavaScript -> "Function and Global Variable Declaration" of the page, but not run.
<script language="JavaScript" type="text/javascript">
function setValueDisplayImage(){
if ($("#SELECT_LIST").val() == 1) {
$("#DISPLAY_IMAGE").val('http://www.some.com/img1.jpg');
} else if ($("#SELECT_LIST").val() == 2) {
$("#DISPLAY_IMAGE").val('https://www.some.com/img2.jpg');
} else if ($("#SELECT_LIST").val() == 3){
$("#DISPLAY_IMAGE").val('http://www.some.com/img3.jpg');
}
}</script>
Use jquery on() like,
$(function(){
$("#SELECT_LIST").on('change', function(){
var val=this.value;
if(val==1 || val==2 || val==3){
$("#DISPLAY_IMAGE").val('http://www.some.com/img'+val+'.jpg');
}
});
});
$(function(){
$("#SELECT_LIST").on('change', function(){
var val=this.value;
if(val==1 || val==2 || val==3){
$("#DISPLAY_IMAGE").val('http://www.some.com/img'+val+'.jpg');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="SELECT_LIST">
<option value="1">First Image</option>
<option value="2">Second Image</option>
<option value="3">Third Image</option>
</select>
<br/>
<input id="DISPLAY_IMAGE" style="width:250px;"/>
And if your DISPLAY_IMAGE element is an img then your need to use attr() to change the image src like,
$(function(){
$("#SELECT_LIST").on('change', function(){
var val=this.value;
if(val){
$("#DISPLAY_IMAGE").attr('src','http://placehold.it/250x'+val);
}
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="SELECT_LIST">
<option value="">Select</option>
<option value="100">First Image</option>
<option value="150">Second Image</option>
<option value="200">Third Image</option>
</select>
<br/>
<img id="DISPLAY_IMAGE"/>

country state drop down not working while editing using select-2 plugin

I am using counties.js form here and using select-2 plugin for drop down.
code for selecting country from the country drop down
<select class="select2 dep" name="country" id="country_list">
<optgroup label="Country">
<option value="">Select Country</option>
<script src="<?=base_url()?>assets/js/countries_states.js"></script>
<script language="javascript">
populateCountries("country_list");
var country_select = document.getElementsByName('country');
for(var m=0;m<country_select[0].options.length;m++)
{
if(country_select[0].options[m].value == '<?=$bhandar_details[0]['country']?>')
{
country_select[0].options[m].setAttribute("selected","true");
}
}
</script>
</optgroup>
</select>
and the code for default selection of states is as follows
<select class="select2 dep" name="state" id="state_list">
<optgroup label="State">
<option value="">Select State</option>
<script language="javascript">
populateStates("country_list", "state_list");
var state_select = document.getElementsByName('state');
for(var m=0;m<state_select[0].options.length;m++)
{
if(state_select[0].options[m].value == '<?=$bhandar_details[0]['state']?>')
{
state_select[0].options[m].setAttribute("selected","true");
}
}
</script>
</optgroup>
when the country is changed its respective states should change for that following script is written
<script type="text/javascript">
$( "#country_list" ).change(function() {
populateStates("country_list", "state_list");
});
</script>
everything works well and fine and when country is changed its respective states are populated in the state drop down. but the display text in state dropdown remains the same even though that state doesnot exists, until not changed manually to some other text.
Ideally as soon as country is changed the state list should change to default selection.
thank you all in advance. waiting for response...
I think what you do to the main select (behind the graphical select2) does not affect the select2 user interface.
In fact, you have to change the value of your select using the plugin itself.
Use this:
$("#state_list").select2().val(0); // any value you like
Working code:
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/select2.min.js"></script>
<script src="js/countries_states.js"></script>
<link href="css/select2.css" rel="stylesheet"/>
<select class="select2 dep" name="country" id="country_list" style="width: 260px;">
<optgroup label="Country">
<option value="">Select Country</option>
</optgroup>
</select>
<select class="select2 dep" name="state" id="state_list">
<optgroup label="State">
<option value="">Select State</option>
</optgroup>
<script type="text/javascript">
$( "#country_list" ).change(function() {
populateStates("country_list", "state_list");
$("#state_list").select2().val(0); //----- added this code
});
$(document).ready(function() {
populateCountries("country_list", "state_list");
$("#country_list").select2();
$("#state_list").select2();
});
</script>
Try this this can help you by just doing a small effort
https://rubygems.org/gems/country_state_select

Disabled input tag based on dropdown value is not working

I'm going to create a dropdown list that contains four values (One, Two, Three, Four). When user chooses (One, Two or Three), the textbox below the dropdown list must allow user to type any text in it; but when user chooses Four, textbox should be disabled.
Here is my code
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script>
var $inputs = $('#myclass');
$('#select').change(function(){
$inputs.prop('disabled', $(this).val() === '4');
});
</script>
<title>Choose one</title>
</head>
<body>
<select id="select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
<input type="text" id="myclass"/>
</body>
</html>
The code above is not working. Can anyone help me to solve this problem?
The DOM isn't ready :
$(function() {
$('#select').on('change', function(){
$('#myclass').prop('disabled', this.value == '4');
});
});
Your JavaScript code is being executed before the DOM is rendered.
Quick fix: place your JavaScript code at the end of the <body> tag. Like this:
<!DOCTYPE html>
<html>
<head>
<title>Choose one</title>
</head>
<body>
<select id="select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
<input type="text" id="myclass"/>
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script>
var $inputs = $('#myclass');
$('#select').change(function(){
$inputs.prop('disabled', $(this).val() === '4');
});
</script>
</body>
</html>
Another option is making JavaScript code to be executed when document is ready, but the "Quick fix" approach is quite popular nowadays. This would be the different (classical?) approach:
<script>
$(document).ready(function () {
var $inputs = $('#myclass');
$('#select').change(function(){
$inputs.prop('disabled', $(this).val() === '4');
});
});
</script>

Categories