I am pretty new to JavaScript. I am trying to create dropdowns that are dynamic in the sense that when you select a value in the first dropdown the second dropdown automatically updates for all possible values for the value selected and vice versa.
I am able to do it one way but not the other way around. Please find attached the screenshot of my code here. I would be grateful for any answers. Thanks.
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
if (s1.value!=""){
if (s1.value!=""){
s2.innerHTML=""
} else {
s1.innerHTML=""
}
if(s1.value == "Chevy"){
var optionArray = ["|","Camaro|Camaro","Corvette|Corvette","Impala|Impala"];
} else if(s1.value == "Dodge"){
var optionArray = ["|","Avenger|Avenger","Challenger|Challenger","Charger|Charger"];
} else if(s1.value == "Ford"){
var optionArray = ["|","Mustang|Mustang","Shelby|Shelby"];
}
for(var option in optionArray){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
if(s2.value == "Camaro" || s2.value=="Corvette"|| s2.value=="Impala"){
var optionArray1 = ["|","Chevy|Chevy"];
} else if(s2.value == "Avenger" || s2.value=="Challenger"|| s2.value=="ImpChargerala"){
var optionArray1 = ["|","Dodge|Dodge"];
} else if(s2.value == "Mustang" || s2.value=="MuShelby"){
var optionArray1 = ["|","Dodge|Dodge"];
}
for(var option in optionArray1){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s1.options.add(newOption);
}
}
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id,'slct2')">
<option value=""></option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2">
<option value=""></option>
<option value="Camaro">Camaro</option>
<option value="Corvette">Dodge</option>
<option value="Impala">Impala</option>
<option value="Avenger">Avenger</option>
<option value="Corvette">Dodge</option>
<option value="Challenger">Challenger</option>
<option value="Charger">Charger</option>
<option value="Mustang">Mustang</option>
<option value="Shelby">Shelby</option>
</select>
<hr />
Hopefully this should explain a lot. See the comments for why certain parts work the way they do.
This code could be shorter, but I wanted to make it more clear. (For more info about almost any JS feature, MDN is a good source. You can google the feature's name and MDN (like "Arrays MDN") to find results on that site.)
const
// Identifies HTML elements in the DOM that we will need
makesDropdown = document.getElementById("makesDropdown"),
modelsDropdown = document.getElementById("modelsDropdown"),
// Puts Makes and Models in a `cars` object for reference
cars = {
Chevy: ["Camaro", "Corvette", "Impala"],
Dodge: ["Avenger", "Challenger", "Charger"],
Ford: ["Mustang", "Shelby"]
}
;
// Calls the appropriate function when a selection changes
makesDropdown.addEventListener("change", updateModelsDropdown);
modelsDropdown.addEventListener("change", updateMakesDropdown);
// Defines listener functions
function updateModelsDropdown(event){
let
// The "target" of the `change` event is the input that changed
thisMake = event.target.value,
// Gets the array of models from `cars` (If no make is selected, uses all models)
relevantModels = cars[thisMake] || getAllModels();
modelsDropdown.selectedIndex = 0; // Shows the first (blank) option
// The select element's children are the options
let optionElements = modelsDropdown.children;
for(let option of optionElements){
// Uses CSS to hide (or unhide) HTML elements
option.classList.add("hidden");
// Keeps the blank option as well as the ones included in the array
if(relevantModels.includes(option.value) || option.value === ""){
option.classList.remove("hidden");
}
}
}
function updateMakesDropdown(event){
let
thisModel = event.target.value,
relevantMake = "",
// Gets an array of the "keys" for an object
allMakes = Object.keys(cars);
// Loops through the keys and tests each corresponding value (ie, each array of models)
for(let make of allMakes){
let models = cars[make];
// Finds the key whose value includes the selected model
if(models.includes(thisModel)){
// Saves the name of the key so we can select it in the makesDropdown
relevantMake = make;
}
}
let optionElements = makesDropdown.children;
for(let i = 0; i < optionElements.length; i++){
// Finds the index of the matching value
if(relevantMake === optionElements[i].value){
// Selects the option by its index
makesDropdown.selectedIndex = i;
}
}
}
// Defines a helper function
function getAllModels(){
// Gets an array of the "keys" for an object
const makes = Object.keys(cars);
const models = []; // Starts with an empty array to push models into
for(let make of makes){
// `cars[make]` retrieves the value (array of models) for that key
// `...` spreads the array into individual values (models)
// `push` adds each model to the new `models` array
models.push(...cars[make]);
}
return models;
}
.hidden{ display: none; }
<hr />
<h2>Choose Your Car</h2>
<hr /> Choose Car Make:
<select id="makesDropdown">
<option value=""></option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr /> Choose Car Model:
<select id="modelsDropdown">
<option value=""></option>
<option value="Camaro">Camaro</option>
<option value="Corvette">Corvette</option>
<option value="Impala">Impala</option>
<option value="Avenger">Avenger</option>
<option value="Challenger">Challenger</option>
<option value="Charger">Charger</option>
<option value="Mustang">Mustang</option>
<option value="Shelby">Shelby</option>
</select>
Note:
Selecting the blank option in the "makesDropdown" automatically resets the "modelsDropdown" so all models are available for the next selection, as one might expect. However, selecting the blank option in the modelsDropdown has no such effect. How would you add this feature to improve user experience?
How can I pass the label, not the option, to have javascript preselect from a dropdown?
For example, let's say the URL is page.html?option=name3
and in the form there's a select like this
<select id="select-box">
<option value="1">Name1</option>
<option value="2">Name2</option>
<option value="3">Name3</option>
<option value="4">Name4</option>
</select>
In this example Name3 and 3 are different.
What javascript could be used to preselect the option whose text contents match that of the URL parameter above?
Read the query param from the current page's URL: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
const optionParam = new URLSearchParams(window.location.search).get('option'); // "Name3"
and than set the Select value to the option which textContent matches
// const optionParam = new URLSearchParams(window.location.search).get('option');
const optionParam = "Name3"; // (PS: Use the above one instead, this is for demo)
const sel = document.getElementById("select-box");
const opt = [...sel.options].find(op => op.textContent===optionParam);
if (opt) sel.value = opt.value;
<select id="select-box">
<option value="1">Name1</option>
<option value="2">Name2</option>
<option value="3">Name3</option>
<option value="4">Name4</option>
</select>
You need to set the selectedIndex of your element using javascript as follows. First, parse the url to get the desired query option. You can use window.location API to get the url and do your operations on it. Then, iterate through each option of your select element and determine a good match using some logic.
I hope this helps.
<select id="select-box">
<option value="1">Name1</option>
<option value="2">Name2</option>
<option value="3">Name3</option>
<option value="4">Name4</option>
</select>
<script>
// to get option we use some parsing:
function getOption(url) {
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
if (queryString){
var optionString = queryString.split('=')[1];
// returns string for options if specified.
return optionString;
}
// return null otherwise.
return null;
}
var e = document.getElementById("select-box");
// var o = getOption(window.location.href);
// var o = getOption(document.url) // does not work for Firefox
// replace this with one of the lines above for dynamic solution
var o = getOption('page.html?option=name3');
if(o) {
for(var i=0; i<e.options.length; i++) {
if(o === e.options[i].innerHTML.toLowerCase()){
// be careful about case sensitivity and try to come up
// with your own logic on how you validate this,
document.getElementById("select-box").selectedIndex = i;
}
}
}else {
// if no option default to 0
document.getElementById("select-box").selectedIndex = 0;
}
</script>
I have Two selected option: the first is contact and the second is contact2. the element in the first select option will be added to the second list.
the function bellow let me to add all element without problems, but I want to add just the element with unique id, because the first list contain many duplicate option id.
function addAllElement(object){
contacts = document.getElementById('contact');
long = object.options.length;
for (i=0;i<long;i++){
txt = object.options[i].text;
valor = object.options[i].value;
idd=object.options[i].id;
addOption(contact2,i,idd,txt,valor);
}
}
this is an example of the list with duplicate id
<select name="contacts" id="contacts" multiple="">
<option value="7147582,2" id="77">Test</option>
<option value="7189466,2" id="62">test2</option>
<option value="7" id="62">contact3</option>
<option value="72" id="64">ERRZERZE, zerzerze</option>
<option value="71" id="62">contact 5</option>
<option value="72y" id="001">contact 6</option>
</select>
As you see many element with the same id, and the predicted result is a list without duplicate element
I would create an array that stores each id per iteration. If the id has already been created, then do not add that to the second select. Redo your function in this manner:
function addAllElement(object) {
var i, valor, idd, txt;
var long = object.options.length;
var ids = [];
for (i = 0; i < long; i++) {
txt = object.options[i].text;
valor = object.options[i].value;
idd = object.options[i].id;
if (ids.indexOf(idd) == -1) {
addOption("contact2", i, idd, txt, valor);
ids.push(idd);
}
}
}
You can check for the length of element with that id before calling addOption method:
for (i=0;i<long;i++){
txt = object.options[i].text;
valor = object.options[i].value;
idd=object.options[i].id;
if(document.getElementById(idd).length)
addOption(contact2,i,idd,txt,valor);
}
im trying to get multiple options on a multiple select and add them in a normal select but when i click on a button to add, for exemple, i select on two options and add them they change to one option on the normal select
JSFIDDLE EXAMPLE
JavaScript CODE
function addProf() {
// get reference to select element
var sel = document.getElementById('ProfAdd');
var opt = document.createElement('option'); // create new option element
// create text node to add to option element (opt)
if ($(this).find('option[value="' + sel + '"]').length == 0) {
opt.appendChild(document.createTextNode(document.getElementById('selProf').value));
opt.value = 'option val'; // set value property of opt
sel.appendChild(opt); // add opt to end of select box (sel)
$("#selProf").find('option:selected').remove();
}
}
function remProf() {
// get reference to select element
var sel = document.getElementById('selProf');
var opt = document.createElement('option'); // create new option element
// create text node to add to option element (opt)
if ($(this).find('option[value="' + sel + '"]').length == 0) {
opt.appendChild(document.createTextNode(document.getElementById('ProfAdd').value));
opt.value = $("#ProfAdd :selected").text(); // set value property of opt
opt.text = $("#ProfAdd :selected").text();
sel.appendChild(opt); // add opt to end of select box (sel)
$("#ProfAdd").find('option:selected').remove();
}
}
HTML CODE
<div class="form-group">
<label for="InputProf">Adicionar professores à turma</label>
<select id="selProf" class="form-control" required>
<option disabled selected>Professor</option>
<option value="2">2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<input type="button" id="button6" class="myButton2" onclick="addProf()" value="Adicionar Professor">
</br>
<div class="form-group">
<label for="InputTurma">Professores adicionados</label>
<select multiple class="form-control" id="ProfAdd">
</select>
</div>
<input type="button" id="button7" class="myButton2" onclick="remProf()" value="Retirar Professor">
If you have two options selected, $('select :selected').text() will return a single string concatenated selected text's. See fiddle.
Because :selected is returning multiple elements, you'll want to loop through them, and do something with each. One way of doing this is using jQuery.each.
You'll need to create a new option for each selected one - I've moved a little
$("#ProfAdd :selected").each(function (idx, selOpt) {
var opt = document.createElement('option'); // create new option element
opt.appendChild(document.createTextNode(document.getElementById('ProfAdd').value));
opt.value = $(selOpt).text(); // set value property of opt
opt.text = $(selOpt).text();
sel.appendChild(opt); // add opt to end of select box (sel)
$(selOpt).remove();
});
http://jsfiddle.net/daveSalomon/0b0obyra/5/
The code still isn't ideal - you're mixing document.getElementById (vanilla JS) with $('#id') (jQuery). Pick one and stick to it.
Here's a much cleaner solution...
var $multiSel = $('#ProfAdd');
var $singleSel = $('#selProf');
$('#button6').click(function(){
var $opts = $singleSel.find('option:selected');
$multiSel.append($opts).val('');
});
$('#button7').click(function(){
var $opts = $multiSel.find('option:selected');
$singleSel.append($opts).val('');
});
http://jsfiddle.net/daveSalomon/0b0obyra/8/
I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P