How to hide\show specific value of option based on another selected option by JQuery? - javascript

I Have html select form like this:
<label>Num:</label>
<select id="id_num">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value=''>all</option>
</select>
<label>Choices:</label>
<select id="id_choices">
<option value='car'>car</option>
<option value='bike'>bike</option>
<option value='house'>house</option>
<option value='money'>money</option>
<option value='plane'>plane</option>
<option value='wife'>wife</option>
</select>
In my case I need to make it so that if I choose "1" at the first select form (# id_num), then the next select form (#id_choices) should only show "car" and "bike" options, and if I choose "2", #id_choices should only show "house" and "money", and also the rest.. But if i select "all", then every options on #id_choices should be shown.
How to solve that condition by using jQuery?

You can use jQuery's $.inArray() to filter your options, and make them display: none; depending upon the occurence of the item in the array,
Please have a look on the code below:
$(function() {
$('#id_num').on('change', function(e) {
if ($(this).val() == 1) {
var arr = ['car', 'bike'];
$('#id_choices option').each(function(i) {
if ($.inArray($(this).attr('value'), arr) == -1) {
$(this).css('display', 'none');
} else {
$(this).css('display', 'inline-block');
}
});
} else if ($(this).val() == 2) {
var arr = ['house', 'money'];
$('#id_choices option').each(function(i) {
if ($.inArray($(this).attr('value'), arr) == -1) {
$(this).css('display', 'none');
} else {
$(this).css('display', 'inline-block');
}
});
} else if ($(this).val() == 3) {
var arr = ['plane', 'wife'];
$('#id_choices option').each(function(i) {
if ($.inArray($(this).attr('value'), arr) == -1) {
$(this).css('display', 'none');
} else {
$(this).css('display', 'inline-block');
}
});
} else {
$('#id_choices option').each(function(i) {
$(this).css('display', 'inline-block');
});
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Num:</label>
<select id="id_num">
<option disabled selected>Select</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value=''>all</option>
</select>
<label>Choices:</label>
<select id="id_choices">
<option value='car'>car</option>
<option value='bike'>bike</option>
<option value='house' >house</option>
<option value='money' >money</option>
<option value='plane' >plane</option>
<option value='wife' >wife</option>
</select>
Hope this helps!

You can run a function once when the page loads and then every time #id_num changes, such that all the visible #id_choices options are removed (using remove()), and then only the relevant options are re-added to #id_choices (using append()) to replace them.
Working Example:
$(document).ready(function(){
var car = '<option value="car">car</option>';
var bike = '<option value="bike">bike</option>';
var house = '<option value="house">house</option>';
var money = '<option value="money">money</option>';
var plane = '<option value="plane">plane</option>';
var wife = '<option value="wife">wife</option>';
function options1() {
$('#id_choices').append(car);
$('#id_choices').append(bike);
}
function options2() {
$('#id_choices').append(house);
$('#id_choices').append(money);
}
function options3() {
$('#id_choices').append(plane);
$('#id_choices').append(wife);
}
function displayOptions() {
$('#id_choices option').remove();
switch ($('#id_num option:selected' ).text()) {
case('1') : options1(); break;
case('2') : options2(); break;
case('3') : options3(); break;
case('all') : options1(); options2(); options3(); break;
}
}
$('#id_num').change(function(){displayOptions();});
displayOptions();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Num:</label>
<select id="id_num">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value=''>all</option>
</select>
<label>Choices:</label>
<select id="id_choices">
<option value='car'>car</option>
<option value='bike'>bike</option>
<option value='house'>house</option>
<option value='money'>money</option>
<option value='plane'>plane</option>
<option value='wife'>wife</option>
</select>
For the sake of completeness, here is the same approach as above, but this time in native javascript, so you can compare and contrast with the jQuery above:
var numbers = document.getElementById('id_num');
var choices = document.getElementById('id_choices');
function displayOptions() {
var optionSet1 = ['car', 'bike'];
var optionSet2 = ['house', 'money'];
var optionSet3 = ['plane', 'wife'];
var oldOptions = choices.getElementsByTagName('option');
var selected = numbers.options[numbers.selectedIndex].text;
while (oldOptions.length > 0) {
choices.removeChild(oldOptions[0]);
}
switch (selected) {
case('1') : var optionSet = optionSet1; break;
case('2') : optionSet = optionSet2; break;
case('3') : optionSet = optionSet3; break;
case('all') : optionSet = optionSet1.concat(optionSet2).concat(optionSet3); break;
}
for (var i = 0; i < optionSet.length; i++) {
var option = document.createElement('option');
option.setAttribute('value',optionSet[i]);
option.textContent = optionSet[i];
choices.appendChild(option);
}
}
numbers.addEventListener('change',displayOptions,false);
window.addEventListener('load',displayOptions,false);
<label>Num:</label>
<select id="id_num">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value=''>all</option>
</select>
<label>Choices:</label>
<select id="id_choices">
<option value='car'>car</option>
<option value='bike'>bike</option>
<option value='house'>house</option>
<option value='money'>money</option>
<option value='plane'>plane</option>
<option value='wife'>wife</option>
</select>

Add the attribute display with a value of none using .prop() instead of using disabled attribute (like in Saumya's answer) in case you want them completely invisible instead of just disabled/grayed-out

there may be a better way, however this does work.. you can also add hide/display classes to any other elements
$(document).ready(function () { $('#id_num').on('change', change) });
function change() {
$('#id_choices > option').hide();
$($(this).find(':selected').attr('clssval')).show();
}
.sel{display:none;}
.num1{display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Num:</label>
<select id="id_num">
<option value='1' clssval=".num1">1</option>
<option value='2' clssval=".num2">2</option>
<option value='3' clssval=".num3">3</option>
<option value='' clssval=".num1,.num2,.num3">all</option>
</select>
<label>Choices:</label>
<select id="id_choices">
<option value='car' class="sel num1">car</option>
<option value='bike' class="sel num1">bike</option>
<option value='house' class="sel num2">house</option>
<option value='money' class="sel num2">money</option>
<option value='plane' class="sel num3">plane</option>
<option value='wife' class="sel num3">wife</option>
</select>

Related

How to show only data-subtext matching with a selected option value - jQuery

I have a dropdown menu that looks like the following:
<select name="category" id="category">
<option value="category-1">category-1</option>
<option value="category-2">category-3</option>
<option value="category-3">category-2</option>
</select>
<select name="product" id="product">
<option data-subtext="category-1">product</option>
<option data-subtext="category-1">product</option>
<option data-subtext="category-2">product</option>
<option data-subtext="category-2">product</option>
<option data-subtext="category-3">product</option>
<option data-subtext="category-3">product</option>
</select>
how do I show only products matching data-subtext with its category value?
You need the hide and show it based on the selected value
$('select[name=category]').on('change', function (event) {
let selectedValue;
selectedValue = $(this).find('option:selected').text();
$('select[name=product] option').filter(function () {
if ($(this).attr('data-subtext') !== selectedValue) {
return true;
} else {
$(this).show();
this.selected = true;
}
}).hide()
});

How to hide select option based on option selected in the first selection

I have two selection dropdown. User have to select the category first, than the sub category option will be displayed based on the first selection.
If user pick category with value 3 it will display the sub category with option value of 1, 2 , 3. Option value of 0 will be hide/ remove in the sub category.
And if user pick category with option 0||1||2 it will only display other in the sub category option.
How do I achieve this. Do I have to use hide function to hide the value ?
$('#category').change(function() {
let cat = $(this).val();
if (cat === '0' || cat === '1' || cat === '2') {
console.log("other");
$("#sub_category").change(function() {
$('#sub_category').children('option[value="1"]').hide();
$('#sub_category').children('option[value="2"]').hide();
$('#sub_category').children('option[value="3"]').hide();
});
} else {
$("#sub_category").change(function() {
$('#sub_category').children('option[value="0"]').hide();
})
console.log(cat);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="category" id="category">
<option value="0">Type A</option>
<option value="1">Type B</option>
<option value="2">Type C</option>
</select>
<select name="sub_category" id="sub_category">
<option value="" hidden>Select Sub Category</option>
<option value="0">Other</option>
<option value="1">Op1</option>
<option value="2">Op2</option>
<option value="3">Op3</option>
</select>
This is what I have tried but its not working
I will get #category value and run for each option to show/hide depending on cat value.
You can use the below demo:
$('#category').change(function() {
$("#sub_category").val('');
let cat = $(this).val();
$("#sub_category option").show();
if (cat == 3) {
$("#sub_category option").each(function (index, item) {
var value = parseInt($(item).val());
if ([0].includes(value)) {
$(item).hide();
}
});
} else {
$("#sub_category option").each(function (index, item) {
var value = parseInt($(item).val());
if ([1, 2, 3].includes(value)) {
$(item).hide();
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="category" id="category">
<option value="0">Type A</option>
<option value="1">Type B</option>
<option value="2">Type C</option>
<option value="3">Value 3</option>
</select>
<select name="sub_category" id="sub_category">
<option value="">Select Sub Category</option>
<option value="0">Other</option>
<option value="1">Op1</option>
<option value="2">Op2</option>
<option value="3">Op3</option>
</select>
Your JS code must look like this.
$('#category').change(function(e) {
let cat = e.currentTarget.value;
if (cat === '0' || cat === '1' || cat === '2') {
$('#sub_category').children('option[value="0"]').show();
$('#sub_category').children('option[value="1"]').hide();
$('#sub_category').children('option[value="2"]').hide();
$('#sub_category').children('option[value="3"]').hide();
} else {
$('#sub_category').children('option[value="1"]').show();
$('#sub_category').children('option[value="2"]').show();
$('#sub_category').children('option[value="3"]').show();
$('#sub_category').children('option[value="0"]').hide();
console.log(cat);
}
});

'selected' attribute for options doesn't reset inside if else statement

I am trying to use an if else statement to add 'selected' to an option from the select menu. The only problem I have is that I'm not sure why once I go back to value 'top' option[1] is still 'selected'. It's like the first if doesn't execute the condition, although i see if i do the console log it does change to the first if...
<select id='selectdesign'>
<option value="0"></option>
<option value="top">top</option>
<option value="jeans">jeans</option>
</select>
<select id='selectmenu'>
<option value="0"></option>
<option value="1">top-blue</option>
<option value="2">top-pink</option>
<option value="3">bottoms-red</option>
<option value="4">bottoms-violet</option>
</select>
function selectOption(element) {
if (element.value == 'top') {
console.log('if');
option[2].setAttribute('selected', true);
} else if (element.value == 'jeans') {
console.log('else if');
option[1].setAttribute('selected', true);
}
}
i am calling the selectOption function on selectDesign on change
You need to access the right value of the select element, like
element.options[element.selectedIndex].value
and use
document.getElementById('selectmenu').selectedIndex = 1;
for setting an index of the options.
function selectOption(element) {
if (element.options[element.selectedIndex].value == 'top') {
document.getElementById('selectmenu').selectedIndex = 1;
} else if (element.options[element.selectedIndex].value == 'jeans') {
document.getElementById('selectmenu').selectedIndex = 3;
}
}
<select id="selectdesign" onchange="selectOption(this);">
<option value="0"></option>
<option value="top">top</option>
<option value="jeans">jeans</option>
</select>
<select id="selectmenu">
<option value="0"></option>
<option value="1">top-blue</option>
<option value="2">top-pink</option>
<option value="3">bottoms-red</option>
<option value="4">bottoms-violet</option>
</select>
Version with an object for preselecting options.
function selectOption(element) {
var indices = {
top: 1,
jeans: 3,
},
value = element.options[element.selectedIndex].value
if (value in indices) {
document.getElementById('selectmenu').selectedIndex = indices[value];
}
}
<select id="selectdesign" onchange="selectOption(this);">
<option value="0"></option>
<option value="top">top</option>
<option value="jeans">jeans</option>
</select>
<select id="selectmenu">
<option value="0"></option>
<option value="1">top-blue</option>
<option value="2">top-pink</option>
<option value="3">bottoms-red</option>
<option value="4">bottoms-violet</option>
</select>

Javascript auto select from dropdown

I'm searching and searching and can not find anything exactly what I need.
So I need javascript, that will select option from dropdown, but not by the option value number, but name.
I have:
<select class="aa" id="local" name="local">
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
So I need to select • Jawor by name, not by id - it's the most important. How do I make it work?
For you is it like;
var options = document.getElementsByClassName("aa")[0].options,
name ="Jawor";
for(i = 0; i < options.length; i++){
if(options[i].text.indexOf(name) > -1){
options[i].selected = true;
break;
}
}
<select class="aa" id="local" name="local">
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
U need to Use onChange Event Handler ... for example
<select onchange="showSelected()">
Then write your script ...
<script>
function showSelected(){
var s=document.getElementById('local'); //refers to that select with all options
var selectText=s.options[s.selectedIndex].text // takes the one which the user will select
alert(selectText) //Showing the text selected ...
}
</script>
Rest of your code is okay !
<select class="aa" id="local" name="local" onchange='showSelected'()>
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
Using jquery here. You can use the following function:
function selectFromDropdown(selector, text) {
$(selector).find('option').each(function() {
if ($(this).text() == text) {
$(selector).val($(this).val());
}
})
}
A demo:
function selectFromDropdown(selector, text) {
$(selector).find('option').each(function() {
if ($(this).text() == text) {
$(selector).val($(this).val());
return false;
}
})
}
//use the function
setTimeout(function() {
selectFromDropdown('#local', '• Dzierżoniów')
}, 1000)
setTimeout(function() {
selectFromDropdown('#local', '• Jawor')
}, 4000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="aa" id="local" name="local">
<option value="">Select</option>
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
for chrome console use this
document.getElementById("id").selectedIndex = '3'; or
document.getElementById('id').value = 'BA';

how to make select box dynamic

I've three select-box here to choose Format, Amount & Shipping type. After selection, it will calculate price automatically.
here, how those select-box look like:
<p>Format: <select class="calculate" name="format">
<option value="0">Please Select</option>
<option value="0">Format 1</option>
<option value="0">Format 2</option>
</select></p>
<p>Amount: <select class="calculate" name="amount">
<option value="0">Select amount</option>
<option value="247">250pcs</option>
<option value="279">1,000pcs</option>
<option value="389">2,500pcs</option>
</select></p>
<p>Shipping type: <select id="surcharge" name="shipping">
<option value="0">Select Shipping</option>
<option value="10%">Standard</option>
<option value="15%">Express</option>
</select></p>
currently, the Amount for the both Format (Format 1/Format 2) are same.
what i'm trying to do is like: for the Format 1, the current Amount will remain same, but if user select Format 2 then the Amount will something like this:
<option value="0">Select amount</option>
<option value="300">250pcs</option>
<option value="350">1,000pcs</option>
<option value="400">2,500pcs</option>
where the value is different! how can i achive this?
here goes the JSfiddle
Thanks in advance for any help!
You should first set the new values in an array. So you can loop through them while changing the first select.
Then you can easily get the options from the 2nd select, and update them with the correct new values:
$(".calculate, #surcharge").on("change", function(){
if($(this).val() == 1)
{
var amountValues = new Array(0,250,400,500);
$("#menge option").each(function(key,value)
{
$(this).val(amountValues[key]);
});
} else if($(this).val() == 2)
{
var amount Values = new Array();
// .....
}
});
http://jsfiddle.net/7Bfk5/15/
You can do this by checking the text() in the options you are selecting
if ($('#sel option:selected').text() === 'Format 2') {
$('#amt option').each(function () {
alert($(this).text());
if ($(this).text() == "250pcs") $(this).val("300");
else if ($(this).text() == "1,000pcs") $(this).val("350");
else $(this).val("400");
});
}
working fiddle
You can create a function that does values/options replacement and call it on your select changes.
I did an example for you but used static html options to replace old ones, this might not be the best way but tried to keep it as simple as possible.
HTML
<p>Format: <select class="calculate format" name="format">
<option value="0">Please Select</option>
<option value="1">Format 1</option>
<option value="2">Format 2</option>
</select></p>
<p>Amount: <select class="calculate amount" name="menge">
<option value="0">Select Menge</option>
<option value="247">250pcs</option>
<option value="279">1,000pcs</option>
<option value="389">2,500pcs</option>
</select></p>
<p>Shipping type: <select id="surcharge" name="shipping">
<option value="0">Select Shipping</option>
<option value="10%">Standard</option>
<option value="15%">Express</option>
</select></p>
<p>Price: <span id="total">0 €</span></p>
Javascript
var updateValues = function (){
if($('.format').val() == 1) {
html = '<option value="300">300pcs</option>';
html += '<option value="400">400pcs</option>';
html += '<option value="500">500pcs</option>';
$('.amount').html(html);
} else if( $('.format').val() == 2) {
html = '<option value="600">600pcs</option>';
html += '<option value="900">900pcs</option>';
html += '<option value="1200">1200pcs</option>';
$('.amount').html(html);
}
};
$('.format').change(function(){updateValues()});
$(".calculate, #surcharge").on("change", function(){
var total = 0;
$('.calculate').each(function() {
if($(this).val() != 0) {
total += parseFloat($(this).val());
}
});
if($('#surcharge').val() != 0) {
total = total * ((100 + parseFloat($('#surcharge').val())) / 100);
}
$('#total').text(total.toFixed(2) + ' €');
});
Fiddle link
http://jsfiddle.net/7Bfk5/23/

Categories