When selecting another country, the list becomes visible. It works, however there's one issue. When selecting another county the very first item of its attached region must be displayed, instead of remained value.
I.e. when selecting Germany, New York must become invisible, and Dresden must become visible. I've been trying to do this for several hours with no luck. Any advice?
$(function() {
$("[name='country']").change(function() {
// Target option
var hiddenClass = 'hidden';
var selected = $(this).find(':selected').data('country-id');
// Hide all options
$("[name='region']").find('option') // Find all options
.addClass(hiddenClass) // Hide them all
.each(function() {
// Find current active
if ($(this).data('country-id') == selected) {
// Show currently matched against selection
$(this).removeClass(hiddenClass);
}
});
}).trigger('change');
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script>
</script>
<select name="country">
<option data-country-id="1">USA</option>
<option data-country-id="2">Germany</option>
</select>
<select name="region">
<option data-country-id="1">New York</option>
<option data-country-id="1">California</option>
<option data-country-id="1">Carolina</option>
<option data-country-id="2">Dresden</option>
<option data-country-id="2">Berlin</option>
</select>
The issue is because, although some of the option elements are hidden, they're still technically available in the DOM to be selected. To fix this you can force the selection to update to the first available option based on the given country-id value.
Also note that you can make your logic more succinct by using filter() instead of an each() loop. Try this:
$(function() {
$("[name='country']").change(function() {
var hiddenClass = 'hidden';
var selected = $(this).find(':selected').data('country-id');
$('[name="region"] option').addClass(hiddenClass)
.filter(`[data-country-id="${selected}"]`).removeClass(hiddenClass)
.first().prop('selected', true);
}).trigger('change');
});
.hidden { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<select name="country">
<option data-country-id="1">USA</option>
<option data-country-id="2" selected="true">Germany</option>
</select>
<select name="region">
<option data-country-id="1">New York</option>
<option data-country-id="1">California</option>
<option data-country-id="1">Carolina</option>
<option data-country-id="2">Dresden</option>
<option data-country-id="2">Berlin</option>
</select>
Related
I have created a dropdown box with 3 options on my website.
I want to change some text on the webpage, depending on the drop-down item selected. For example:
If dropdown option 1 is chosen, I would like some text on the page that says "You have chosen option 1".
I don't know any JavaScript and so I haven't tried anything apart from trying to search for a similar solution.
<select name="os0" style="background: #315d80; color: #fff; border-color: white; border: 0px;">
<option value="op1">Option 1</option>
<option value="op2">Option 2</option>
<option value="op3">Option 3</option>
</select>
Full sultion with jQuery (I started typing it before you added the HTML to your question so the options are italian car brands).
https://jsfiddle.net/mL2c2xb6/
HTML:
<select id="carSelect">
<option></option>
<option value="Audi">Audi</option>
<option value="Ferrari">Ferrari</option>
<option value="Fiat">Fiat</option>
</select>
<p id="choiceDisplay">
Selection Display
</p>
Javascript:
$('select').change(function(){ // Listen to changes to <select> element
const options = $("option"); // Get all the <option> elements.
let selectedOption = ""; // Var to store selected option value.
options.each(function(index){ // Iterate through option elements.
let option = options[index];
if($(option).prop("selected")) { // Find the seletced one.
selectedOption = $(option).val(); // Get the value and store it
};
});
$("#choiceDisplay")
.empty()
.append(selectedOption); // Display the result.
});
var e = document.querySelector('[name="os0"]');
var strUser = "";
e.addEventListener("change", function(){
strUser = e.options[e.selectedIndex].innerHTML;
alert("You have chosen " + strUser);
});
I have many select options lists <select> and on change of one of them I want to apply some action to the others except the current one i.e the active list that triggered change event. I follow code like the following:
<select class="ops">
<option>Select</option>
<option value="1">One</otption>
<option value="2">Two</otption>
<option value="3">Three</otption>
<option value="4">Four</otption>
</select>
<select class="ops">
<option>Select</option>
<option value="1">One</otption>
<option value="2">Two</otption>
<option value="3">Three</otption>
<option value="4">Four</otption>
</select>
<select class="ops">
<option>Select</option>
<option value="1">One</otption>
<option value="2">Two</otption>
<option value="3">Three</otption>
<option value="4">Four</otption>
</select>
<select class="ops">
<option>Select</option>
<option value="1">One</otption>
<option value="2">Two</otption>
<option value="3">Three</otption>
<option value="4">Four</otption>
</select>
<script>
$(document).ready(function(){
var basicObj;
$("select.ops").change(function(){
basicObj = $(this);
$("select.ops").each(function(){
if ($(this) !== basicObj){
// do something
$(this).css('color','red');
}
})
})
})
</script>
The problem here is if ($(this) !== basicObj) always evaluated as true so, for example, when the first select list changed, its color changed to red too! this code demo
Reason why not working :
Note that jQuery selectors return the Jquery collection of selected objects, mean that they never be equal in the sense of reference equality.
To compare Jquery objects, is() function
Description: Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
To check jquery objects equals you should have tried !$(this).is(basicObj)
<script>
$(document).ready(function(){
$("select").change(function(){
var basicObj = $(this);
$("select").each(function(sel){
debugger;
if (!$(this).is(basicObj)){
// do something
$(this).css('color','red');
}
})
})
})
</script>
Demo
I have a select box and add more button. when I click add more button it's creating another select using clone.In first select box I select one option value from select box means that value should be removed from next created select box.At the same time which selected value in select box that current value shown on current select box. Select box value is being loaded dynamically.
Eg:
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
Is it what you're looking for ?
I would recommend you to play and manipulate with index(), that won't bother your dynamic values.
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
$('button').click(function(){
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value="">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Clone</button>
You can try like this.
$("#yourId").val(" ")//if your value has white spec else use like below line
$("#YourId").val("")//What ever you want to be selected, place your value in .val()
I hope this will help you, if you need anything please ask!
$("button").on("click", function() {
$("#section_1")
.clone()
.attr("id", "section_2")
.on("change", function() {
var sec2Val = $(this).val();
var delOption = $("#section_1 > option[value=" + sec2Val + "]").detach();
optionHolder.push(delOption);
})
.insertAfter($("#section_1"));
$(this).attr("disabled", "disabled");
});
var optionHolder = [];
$("#section_1").on("change", function() {
var sec1Val = $(this).val();
if ($("#section_2")) {
var delOption = $("#section_2 > option[value=" + sec1Val + "]").detach();
optionHolder.push(delOption);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Add more</button>
what I'm trying to do is to create two select fields and after selecting some option in the first one, some of options in the second should be hidden.
I'm almost there, except the fact, that my script can't find certain option out of the first select field, but when I put such option in the first it works, but only with the first one, so it's useless. I need it to hide options in the second select field according to option chosen in the first one.
What makes it all more difficult is the fact that I can't add any classes or ids or anything actually here.
I think I've made some mistake that consists of the way I tell the script which element should it edit, but I have no idea how to write it another way.
HTML
<select name="NameOne">
<option value="First">Lorem Ipsum1</option>
<option value="Second">Lorem Ipsum2</option>
<option value="Third">Lorem Ipsum3</option>
<option value="CD">Dolor2</option>
</select>
<select name="NameTwo">
<option value="AB">Dolor1</option>
<option value="CD">Dolor2</option>
<option value="EF">Dolor3</option>
</select>
JS
$("select").change(function(){
if($(this).val() == "Second") {
$('option[value="CD"]', this).addClass('hidden');
} else {
$('option[value="CD"]', this).removeClass('hidden');
}
});
CSS
.hidden {
display: none
}
Please, help.
It is not working because of this code here:
$('option[value="CD"]', this)...
In simple words, this checks for the option on select which is currently clicked. Since you clicked the first select, this becomes the first select and it tries to find option with values CD on it which is not present. So what you do?? Simple, get the second select, find option with values CD in it and change the class :)
Try this
// you can change this to select first select only since selecting all the select doesnot make sense.
$("select").change(function(){
//$("select[name='NameOne']").change(function(){ <--- better
var secondSelect = $("select[name='NameTwo']"); //get second select
if($(this).val() == "Second") {
secondSelect.find('option[value="CD"]').addClass('hidden'); //find option with CD and add Class
} else {
secondSelect.find('option[value="CD"]').removeClass('hidden');
}
});
.hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="NameOne">
<option value="First">Lorem Ipsum1</option>
<option value="Second">Lorem Ipsum2</option>
<option value="Third">Lorem Ipsum3</option>
<option value="CD">Dolor2</option>
</select>
<select name="NameTwo">
<option value="AB">Dolor1</option>
<option value="CD">Dolor2</option>
<option value="EF">Dolor3</option>
</select>
$("select").change(function(){
var secondSelect = $(select["name='NameTwo']");
if($(this).val() == "Second") {
secondSelect.find('option[value="CD"]').addClass('hidden');
} else {
secondSelect.find('option[value="CD"]').removeClass('hidden');
}
});
You should query on a specific select and then hide the option in the other select, without this which would only do those options in the select that changed.
$("select[name='NameOne']").change(function() {
if ($(this).val() == "Second") {
$("select[name='NameTwo'] option[value='CD']").addClass('hidden');
} else {
$("select[name='NameTwo'] option[value='CD']").removeClass('hidden');
}
});
.hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="NameOne">
<option value="First">Lorem Ipsum1</option>
<option value="Second">Lorem Ipsum2</option>
<option value="Third">Lorem Ipsum3</option>
<option value="CD">Dolor2</option>
</select>
<select name="NameTwo">
<option value="AB">Dolor1</option>
<option value="CD">Dolor2</option>
<option value="EF">Dolor3</option>
</select>
I have a "state" select and a few "carrier" selects. for simplicity I'm using only two carrier selects here.
My jquery is suppose to show the carrier selects based on the the state selected.
The state select value is appended to the carrier select name so I can choose which carrier select to add a specific class to.
MY PROBLEM: My carrier selects wont show up. I had this working at one point, and I must've changed something along the way. Not sure whats happening here. Any help would be great. Thanks!
EDIT: I've added my original JS to show where I was, and how I want to change to Jquery.
HTML:
<div style="width:160px;">
<select name="state_select" id="state_select">
<option value="0" selected>Choose a state</option>
<option value="1">Connecticut</option>
<option value="2">New Hampshire</option>
<option value="3">New Jersey</option>
<option value="4">New York</option>
</select>
</div>
<div id="select-div1" class="select-div">
<select name="carrier_select" id="carrier_select1" class="carrier_select">
<option selected disabled>Select a carrier - Conn</option>
<!--PHP GENERATED OPTIONS-->
</select>
</div>
<div id="select-div" class="select-div">
<select name="carrier_select" id="carrier_select2" class="carrier_select">
<option selected disabled>Select a carrier - NH</option>
<!--PHP GENERATED OPTIONS-->
</select>
</div>
JQUERY:
$('#state_select').prop('selectedIndex', 0);
$('.carrier_select').prop('selectedIndex', 0);
function optionCheck() {
stateVal = $('div.select-div select').val();
selectDiv = $('#carrier_select')[0] + stateVal;
if ($(stateVal).attr('selected', 'selected')) {
$(selectDiv).attr('class', "conn_select", "nh_select", "nj_select", "ny_select");
$(selectDiv).addClass("dropdown-box");
} else {
$(selectDiv).attr('class', 'carrier_select');
}
}
$('#state_select').change(function(e) {
$('.carrier_select').prop('selectedIndex', 0);
optionCheck();
});
MY JAVASCRIPT (WORKS) BEFORE TRYING JQUERY:
function optionCheck() {
var i, len, optionVal, selectDiv,
selectOptions = document.getElementById("state_select");
// loop through the options in case there
// are multiple selected values
for (i = 0, len = selectOptions.options.length; i < len; i++) {
// get the selected option value
optionVal = selectOptions.options[i].value;
// find the corresponding help div
selectDiv = document.getElementById("carrier_select" + optionVal);
// move on if I didn't find one
if (!selectDiv) { continue; }
// set CSS classes to show/hide help div
if (selectOptions.options[i].selected) {
selectDiv.className = "conn_select nh_select nj_select ny_select";
$(selectDiv).addClass("dropdown-box");
} else {
//Hide carrier select on page load
selectDiv.className = "carrier_select";
}
}
}
// bind the onchange handler
document.getElementById("state_select").onchange = optionCheck;
CSS:
.select-div select {
border: none;
-webkit-appearance: none;
-moz-appearance: none;
text-indent: 1px;
text-overflow: '';
}
.carrier_select {
display: none;
}
First off, your code has some redundancies and some questionable decisions in it in my humble opinion that you could work around in order to simplify and/or make it more usable. However, there is a way to achieve what you want with most of it untouched, using Javascript/jQuery code. For the full thing, check this fiddle, the script is below as well along with its explanation:
$('#state_select').prop('selectedIndex', 0);
$('.carrier_select').prop('selectedIndex', 0);
function optionCheck() {
stateVal = $('#state_select').val();
selectDiv = $('#carrier_select'+ stateVal);
$('.dropdown-box:not(#state_select_box)').removeClass('dropdown-box').addClass('carrier_select');
$(selectDiv).removeClass('carrier_select').addClass('dropdown-box');
$($selectDiv).val('0');
}
$('#state_select').change(function(e) {
optionCheck();
});
What this does is it gets the val() of #state_select, appends it to the #carrier_select so that the selector targets the right id, then changes all active selectors, except the #state_selector_box (which I made to wrap around #state_select) to ones with the .carrier_select class, thus making them invisible and then it finally makes the one that corresponds to the selected state visible using the dropdown-box class. Also the val() of the selector that just appeared is set to 0.
You are telling css to hide the element
.carrier_select {
display: none;
}
Both of your select elements have the class "carrier_select" and as a result of this css definition, they are not displayed. Remove or change this definition for them to be shown.
Edited in such a way that you can see the carrier selections. But other part of your question - appending to carrier name, showing carriers depending on the state needs more inputs.
$('#state_select').prop('selectedIndex', 0);
$('.carrier_select').prop('selectedIndex', 0);
function optionCheck() {
stateVal = $('div.select-div select').val();
selectDiv = $('#carrier_select')[0] + stateVal;
if ($(stateVal).attr('selected', 'selected')) {
$(selectDiv).attr('class', "conn_select", "nh_select", "nj_select", "ny_select");
$(selectDiv).addClass("dropdown-box");
} else {
$(selectDiv).attr('class', 'carrier_select');
}
}
$('#state_select').change(function(e) {
$('.carrier_select').prop('selectedIndex', 0);
optionCheck();
});
.select-div select {
border: none;
-webkit-appearance: none;
-moz-appearance: none;
text-indent: 1px;
text-overflow: '';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="dropdown-box" style="width:160px;">
<select name="state_select" id="state_select">
<option value="0" selected>Choose a state</option>
<option value="1">Connecticut</option>
<option value="2">New Hampshire</option>
<option value="3">New Jersey</option>
<option value="4">New York</option>
</select>
</div>
<div id="select-div1" class="select-div">
<select name="carrier_select" id="carrier_select1" class="carrier_select">
<option selected disabled>Select a carrier - Conn</option>
<!--PHP GENERATED OPTIONS-->
</select>
</div>
<div id="select-div" class="select-div">
<select name="carrier_select" id="carrier_select2" class="carrier_select">
<option selected disabled>Select a carrier - NH</option>
<!--PHP GENERATED OPTIONS-->
</select>
</div>
Without commenting on the rest of the code, try removing
.carrier_select {
display: none;
}