How to check if changes on multiple select boxes happened - javascript

I have 2 select dropdown boxes. I need to do many iterations if options were selected.
My select boxes:
<select id="time_period">
<option value="day" selected>Day</option>
option value="month">Month</option>
</select>
<select id="site">
<option value="google" selected>Google</option>
option value="bing">Bing</option>
</select>
I want to check if an option from just #time period was selected or an option from #site or even if options from both were selected.
Is there a way to do that?

Using onchange method
(function() {
var time_period, site;
document.getElementById("time_period").onchange = function() {
time_period = document.getElementById("time_period").value;
console.log(time_period);
checkBothSelected();
};
document.getElementById("site").onchange = function() {
site = document.getElementById("site").value;
console.log(site);
checkBothSelected();
};
function checkBothSelected() {
if (site && time_period) {
console.log('Both Selected!');
}
}
})();
<select id="time_period">
<option value="day" selected>Day</option>
<option value="month">Month</option>
</select>
<select id="site">
<option value="google" selected>Google</option>
<option value="bing">Bing</option>
</select>
Using onChange property
var time_period, site;
function onSelection(e) {
if (e.id == 'time_period') {
time_period = e.value;
} else if (e.id == 'site') {
site = e.value;
}
console.log(e.value);
checkBothSelected();
}
function checkBothSelected() {
if (site && time_period) {
console.log('Both Selected!');
}
}
<select id="time_period" onChange="onSelection(this)">
<option value="day" selected>Day</option>
<option value="month">Month</option>
</select>
<select id="site" onChange="onSelection(this)">
<option value="google" selected>Google</option>
<option value="bing">Bing</option>
</select>
Using addEventListener
(function() {
var time_period, site;
document.getElementById('time_period').addEventListener('change', function() {
time_period = this.value;
console.log(time_period);
checkBothSelected();
});
document.getElementById('site').addEventListener('change', function() {
site = this.value;
console.log(site);
checkBothSelected();
});
function checkBothSelected() {
if (site && time_period) {
console.log('Both Selected!');
}
}
})()
<select id="time_period">
<option value="day" selected>Day</option>
<option value="month">Month</option>
</select>
<select id="site">
<option value="google" selected>Google</option>
<option value="bing">Bing</option>
</select>

You can get a function and check for the selected value from each of the select box
function getSelectedRadio() {
let getTimePeriod = $('#time_period').val();
let site = $('#site').val();
// when both are selected
if (getTimePeriod && site) {
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="time_period">
<option value="day" selected>Day</option>
<option value="month">Month</option>
</select>
<select id="site">
<option value="google" selected>Google</option>
<option value="bing">Bing</option>
</select>
<button type='btn' onclick='getSelectedRadio()'>Click</button>

Related

How to disable multiple options in a select based on another select in JavaScript / Jquery

I am using Select2 Jquery plugin. I have to 2 selects tableHeader and tableBody where I can select multiple tags on each.
What I am trying to do is :
If I select an option or more in first select it/they will be disabled in the second select and vice versa, the same if I unselect an option from one select it will be enabled in other select.
What I did is :
I created an array selections where I am storing the selected options from first select then I am looping through the options of second select and check if the value exists in the array then disable it.
The logic should be correct I guess. Just couldn't find out why my options are not disabled. Any suggestions please ?
here is my code with explanation.
$(document).ready(function() {
// this function to search and show matched input
function matchCustom(params, data) {
if ($.trim(params.term) === '') { return data; }
if (typeof data.text === 'undefined') { return null; }
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
var modifiedData = $.extend({}, data, true);
modifiedData.text += '';
return modifiedData; }
return null; }
$(".select2").select2({
matcher: matchCustom
});
//if you select or unselect option trigger this
$('#tableHeader').change(function() {
var selections = [];
// if you select an option then add the value in array
$('#tableHeader').on('select2:select', function (e) {
$('#tableHeader option:selected').each(function(){
if($(this).val())
selections.push($(this).val()); });
});
// if you unselect an option then remove from array
$('#tableHeader').on('select2:unselect', function (e) {
var unselected = e.params.data.id;
selections.splice( $.inArray(unselected, selections), 1 );
});
console.log(selections);
// loop through other select option and check if value exists in array then disable it
$('#tableBody option').each(function() {
if(jQuery.inArray($(this).val(), selections) !== -1) {
console.log($(this).val());
$('#tableBody option[value="'+ $(this).val() + '"]').prop('disabled',true); }
});
});
// do the same if you start with second select
$('#tableBody').change(function() {
var selections = [];
$('#tableBody').on('select2:select', function (e) {
$('#tableBody option:selected').each(function(){
if($(this).val())
selections.push($(this).val()); });
});
$('#tableBody').on('select2:unselect', function (e) {
var unselected = e.params.data.id;
selections.splice( $.inArray(unselected, selections), 1 );
});
console.log(selections);
$('#tableHeader option').each(function() {
if(jQuery.inArray($(this).val(), selections) !== -1) {
console.log($(this).val());
$('#tableHeader option[value="'+ $(this).val() + '"]').prop('disabled',true); }
});
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<span>Table Header</span>
<select id="tableHeader" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>
<br>
<span>Table Body</span>
<select id="tableBody" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>
Your logic while it's in the idea right, I think you're just complicating things for yourself. Just get on each change the values of each select, loop through the other select and disable one by one the ones that have the same value.
$(document).ready(function() {
// this function to search and show matched input
function matchCustom(params, data) {
if ($.trim(params.term) === '') {
return data;
}
if (typeof data.text === 'undefined') {
return null;
}
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
var modifiedData = $.extend({}, data, true);
modifiedData.text += '';
return modifiedData;
}
return null;
}
$(".select2").select2({
matcher: matchCustom
});
$('#tableHeader').change(function() {
var tableHeader = $(this).val();
var tableBody = $("#tableBody")[0];
$.each(tableBody.options, function(i, item) {
if (tableHeader.includes(item.value)) {
$(item).prop("disabled", true);
} else {
$(item).prop("disabled", false);
}
});
});
$('#tableBody').change(function() {
var tableBody = $(this).val();
var tableHeader = $("#tableHeader")[0];
$.each(tableHeader.options, function(i, item) {
if (tableBody.includes(item.value)) {
$(item).prop("disabled", true);
} else {
$(item).prop("disabled", false);
}
});
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<span>Table Header</span>
<select id="tableHeader" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>
<br>
<span>Table Body</span>
<select id="tableBody" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>
Just enable and disable on change event of each other, see below snipet
$(document).ready(function() {
// this function to search and show matched input
function matchCustom(params, data) {
if ($.trim(params.term) === '') { return data; }
if (typeof data.text === 'undefined') { return null; }
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
var modifiedData = $.extend({}, data, true);
modifiedData.text += '';
return modifiedData; }
return null; }
$(".select2").select2({
matcher: matchCustom
});
var disableTableBody = function(value){
$('#tableBody option[value="'+ value +'"]').prop('disabled',true);
};
var enableTableBody = function(value){
$('#tableBody option[value="'+ value +'"]').prop('disabled',false);
};
var disableTableHeader = function(value){
$('#tableHeader option[value="'+ value +'"]').prop('disabled',true);
};
var enableTableHeader = function(value){
$('#tableHeader option[value="'+ value +'"]').prop('disabled',false);
};
$("#tableHeader").change(function(){
disableTableBody($(this).val());
});
$('#tableHeader').on("select2:unselecting", function(e){
enableTableBody($(this).val());
});
$("#tableBody").change(function(){
disableTableHeader($(this).val());
});
$('#tableBody').on("select2:unselecting", function(e){
enableTableHeader($(this).val());
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<span>Table Header</span>
<select id="tableHeader" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>
<br>
<span>Table Body</span>
<select id="tableBody" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>

Calling onclick from options in a dropdown

I have created a dropdown and added a onclick="function name" to each of the options but however on selecting those options from the dropdown I am unable to get any response
This is the code that i have tried using:
<span onclick="myfunc('demo')">Sports</span>
<select name="sports">
<option value="none"></option>
<option value="cricket" onclick="myfunc('cricket')">Cricket</option>
<option value="football" onclick="myfunc('football')">Football</option>
<option value="volleyball" onclick="myfunc('volleyball')">Volleyball</option>
<option value="basketball" onclick="myfunc('basketball')">Basketball</option>
<option value="ttenis" onclick="myfunc('ttennis')">Table Tennis</option>
<option value="athletics" onclick="myfunc('atletics')">Athletics</option>
</select>
function myfunc(ft){
console.log(ft);
}
My only response is when I click the span i.e.Sports, and I get 'demo displayed in the output.
You may use change event to handle your each item. Please follow below code as your need
<select id="ddlSportsItems" name="sports">
<option value="0">None</option>
<option value="1">Cricket</option>
<option value="2">Football</option>
<option value="3">Volleyball</option>
<option value="4">Basketball</option>
<option value="5">Table Tennis</option>
<option value="6">Athletics</option>
</select>
$('#ddlSportsItems').change(function()
{
var selectedValue = parseInt(jQuery(this).val());
switch(selectedValue){
case 1:
Cricket();
break;
case 2:
Football();
break;
//etc...
default:
alert("catch default");
break;
}
});
function Cricket(){
alert("do your require stuff");
}
function Football(){
alert("do your require stuff");
}
Solution in javascript:
<select name="sports" onchange="myFunc(this)">
<option value="none"></option>
<option value="cricket">Cricket</option>
<option value="football">Football</option>
<option value="volleyball">Volleyball</option>
<option value="basketball">Basketball</option>
<option value="ttenis">Table Tennis</option>
<option value="athletics">Athletics</option>
</select>
<script>
function myFunc(select){
console.log(select.value);
}
</script>
Correct way to write this would be :
function myfunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
console.log(selectedValue);
if (selectedValue === 'cricket') {
alert("Cricket");
//Write your code for cricket
}
else if (selectedValue === 'football') {
alert("Football");
}
else if (selectedValue === 'volleyball') {
alert("Volleyball");
}
else if (selectedValue === 'basketball') {
alert("BasketBall")
}
else if (selectedValue === 'ttenis') {
alert("Table Tennis");
}
else if (selectedValue === 'athletics') {
alert("Athletics");
}
}
<span>Sports:</span>
<select id="selectBox" name="sports" onchange="myfunc();">
<option value="none"></option>
<option value="cricket">Cricket</option>
<option value="football">Football</option>
<option value="volleyball">Volleyball</option>
<option value="basketball">Basketball</option>
<option value="ttenis">Table Tennis</option>
<option value="athletics">Athletics</option>
</select>
You can try this.
function myfunc() {
alert($("#selectBox").val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Sports:</span>
<select id="selectBox" name="sports" onchange="myfunc();">
<option value="none"></option>
<option value="cricket">Cricket</option>
<option value="football">Football</option>
<option value="volleyball">Volleyball</option>
<option value="basketball">Basketball</option>
<option value="ttenis">Table Tennis</option>
<option value="athletics">Athletics</option>
</select>

javascript - get selected value from select list

i got a form with a select form elements for month.
<select id="month" name="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option>Mar
<option>Apr
<option>May
<option>Jun
<option>Jul
<option>Aug
<option>Sept
<option>Oct
<option>Nov
<option>Dec
</select>
How do i use javascript to get compare the selected value. for example if i select Feb, the javascript will pop up "you selected feb"
var monthSelect = document.getElementById("month")
var opt = monthSelect.options[monthSelect.selectedIndex]
if(opt.text == "Feb")
{
alert("Feb selected")
return false
}
JSFiddle: https://jsfiddle.net/ebrnh047/
Your html:
<select id="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
</select>
Try:
var month = document.getElementById("month");
month.onchange = function() {
if (month.value == "Feb") {
alert("Feb selected");
}
}
This is a way to do it with JavaScript only:
First, your HTML:
<select id="month" name="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option value="Mar">Mar</option>
<option value="Apr">Apr</option>
<option value="May">May</option>
<option value="Jun">Jun</option>
<option value="Jul">Jul</option>
<option value="Aug">Aug</option>
<option value="Sep">Sep</option>
<option value="Oct">Oct</option>
<option value="Nov">Nov</option>
<option value="Dec">Dec</option>
</select>
Then, your script:
var monthSelect = document.getElementById("month");
monthSelect.onchange = function(){
var thisValue = this.value;
alert(thisValue);
};
This is the fiddle: https://jsfiddle.net/16sn90tp/
Make sure you execute this code on document ready event( window.onload )
var monthSelect = document.getElementById("month")
monthSelect.onchange = function() {
var opt = monthSelect.options[monthSelect.selectedIndex]
if (opt.text == "Feb") {
alert("Feb selected")
}
}
<select id="month" name="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option>Mar
<option>Apr
<option>May
<option>Jun
<option>Jul
<option>Aug
<option>Sept
<option>Oct
<option>Nov
<option>Dec
</select>
Jan Feb
function myFunction() {
var monthSelect = document.getElementById("month").value;
if (monthSelect == "Feb") {
alert("Feb selected");
return false;
}
}
<select id="month" name="month" onchange="myFunction()">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
</select>
Hi add at first a class called "month" to all of your option tags and one class "monthList" to the select like for example this:
<select class="monthList">
<option class="month">Jan</option>
<option class="month">Feb</option>
<option class="month">Mar</option>
...
</select>
After this you need a little bit of JQuery:
$(".monthList .month").click(function(){
var selectedMonth = $(this).text();
var showText = "you selected " + selectedMonth;
alert(showText);
});
Try this, it should work.

dropdown values hide show

I have 2 dropdowns, here is the fiddle,
https://jsfiddle.net/oqsf7gjq/1/
<select id="ddlOption">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/><br/>
<select id="ddlCar">
<option value="">- Please select a name -</option>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
When user selects "Yes" from "ddlOption" dropdown, then I want to show only 2 values (Saab and Audi) for dropdown "ddlCar" and when user selects "No", then I want to see all values for "ddlCar" dropdown.
Please suggest me any possibilities with Jquery code. Thanks!
jsFiddle example
$("#ddlOption").change(function() {
$("#ddlCar").val("").find("[value=1], [value=3]").toggle( this.value==="2" );
});
$("#ddlOption").change(function() {
$("#ddlCar").val("").find("[value=1], [value=3]").toggle( this.value==="2" );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlOption">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/><br/>
<select id="ddlCar">
<option value="">- Please select a name -</option>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
Toggle the desired option elements by checking Boolean the first select's value (this.value==="2")
Also, reset to .val("") in order to make sure the second select value is properly cleared from possible previous changes.
$('#ddlOption').change(function(){
var txt = $(this).val();
alert(txt);
if(txt==1){
$('#ddlCar option[value="1"]').hide();
$('#ddlCar option[value="3"]').hide();
}
else{
$('#ddlCar option[value="1"]').show();
$('#ddlCar option[value="3"]').show();
}
});
Fiddle
http://jsfiddle.net/ue4Cm/38/
Tested in Edge, Chrome, Firefox and Internet Explorer 11
Note that hiding and showing the options doesn't work in Edge or IE. The elements need to be really removed.
$(function() {
var $ddlCar = $("#ddlCar");
var $ddlCarOptions = $ddlCar.children("option");
$("#ddlOption").change(function() {
if ($(this).val() === "1") {
$ddlCarOptions.filter(".toggleable").attr("selected", false).remove();
} else {
$ddlCar.empty().append($ddlCarOptions);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlOption">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/>
<br/>
<select id="ddlCar">
<option value="">- Please select a name -</option>
<option class="toggleable" value="1">Volvo</option>
<option value="2">Saab</option>
<option class="toggleable" value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
Check updated fiddle
In your markup, you need to add classes to the dropdown values first
<select id="ddlOption">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/><br/>
<select id="ddlCar">
<option value="">- Please select a name -</option>
<option value="1">Volvo</option>
<option value="2" class="yes">Saab</option>
<option value="3">Mercedes</option>
<option value="4" class="yes">Audi</option>
</select>
In your jquery code now
$(function() {
$("#ddlOption").change(function() {
var selectedValue = $(this).val();
if (selectedValue == 1)
{
$("#ddlCar option").hide();
$("#ddlCar option.yes").show();
}
else
{
$("#ddlCar option").show();
}
});
});
please check the code below I have made few changes to your code
<script type="text/javascript">
function populateList() {
if($("option:selected",$("#ddlOption")).val()=="1")
{
$(".val1").hide();
$(".val2").show();
}
else if($("option:selected",$("#ddlOption")).val()=="2")
{
$(".val1").show();
$(".val2").hide();
}
else
{
$(".val1").show();
$(".val2").show();
}
}
</script>
<select id="ddlOption" onchange="populateList();">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/><br/>
<select id="ddlCar">
<option value="">- Please select a name -</option>
<option value="1" class="val2">Volvo</option>
<option value="2" class="val1">Saab</option>
<option value="3" class="val2">Mercedes</option>
<option value="4" class="val1">Audi</option>
</select>
let me know if you have any doubts
You can write code as below which is also works for larger object value(300 or whatever size) and it is dynamic.
Here optionOne, optionTwo are object which is bind when Yes/No value selected
Updated Js fiddle link
$(function() {
var optionOne=[{text:"Saab",value:"2"},{text:"Audi",value:"4"}];
var optionTwo=[{text:"Volvo",value:"1"},{text:"Saab",value:"2"},{text:"Mercedes",value:"3"},{text:"Audi",value:"4"}];
$("#ddlOption").change(function() {
var selectedValue=$(this).val();
$('#ddlCar').html('');
var mySelect = $('#ddlCar').append($('<option></option>').val("").html("- Please select a name -"));
if(selectedValue==='1'){
$.each(optionOne, function(index, item) {
mySelect.append($('<option></option>').val(item.value).html(item.text));
});
}else if(selectedValue==='2'){
$.each(optionTwo, function(index, item) {
mySelect.append($('<option></option>').val(item.value).html(item.text));
});
}else{
//To Do if no selection
}
});
});
Try this: https://jsfiddle.net/oqsf7gjq/17/ not the cleanest solution but it will work cross browsing.
$(function() {
var carArray = [];
$('#ddlCar option').each(function() {
carArray.push($(this));
});
$("#ddlOption").change(function() {
if ($('#ddlOption').val() == 1) {
$('#ddlCar option').each(function() {
if ($(this).val() != 2 && $(this).val() != 4) {
$(this).remove();
}
})
} else {
$('#ddlCar option').each(function() {
$(this).remove();
})
for (var i in carArray) {
$('#ddlCar').append(carArray[i])
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlOption">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/>
<br/>
<select id="ddlCar">
<option value="0">- Please select a name -</option>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>

jQuery remove SELECT options based on another SELECT selected (Need support for all browsers)

Say I have this dropdown:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I want it so that when the user selects 1, this is the thing that the user can choose for dropdown 2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
Or if the user selects 2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
</select>
Or if the user selects 3:
<select id="theOptions2">
<option value="b">b</option>
<option value="c">c</option>
</select>
I tried the code posted here:
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
But it doesn't work for selects.
Please help!
Thank you!
UPDATE:
I really like the answer Paolo Bergantino had on:
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
Is there anyway to modify this to work with selects instead of radio buttons?
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)
);
}
});
});
});
};
This works (tested in Safari 4.0.1, FF 3.0.13):
$(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;
}
});
});
And the beautiful UI:
<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>
You can add classes to your <option>s to store which go with each value of #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>
then do this:
$(function() {
var allOptions = $('#theOptions2 option').clone();
$('#theOptions1').change(function() {
var val = $(this).val();
$('#theOptions2').html(allOptions.filter('.option-' + val));
});
});
For the record you can NOT remove options in a select list in Internet Explorer.
try this. this will definitely work
$(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>
Actually, using the code below will remove a dropdown option just fine in IE, as long as it is not the selected option (it will not work on "a" without deselecting that option first):
var dropDownField = $('#theOptions2');
dropDownField.children('option:contains("b")').remove();
You just run this to remove whatever option you want to remove under a conditional statement with the first group (theOptions1) - that if one of those is selected, you run these lines:
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

Categories

Resources