JavaScript Reset a dropdown to it's default option - javascript

I have the following dropdown in HTML:
<div class="drop-down-container">
<span>Select Employee: </span>
<select
class="drop-down"
id="employees-list"
onchange="populateTable();"
>
<option selected disabled>--Select--</option>
</select>
</div>
And the JS which populates the dropdown with a list of employees:
// Loop through all employees and display them on the dropdown
for (var i = 0; i < getResources.length; i++) {
let option = document.createElement("option");
option.text = getResources[i].children[1].textContent;
empList.options.add(option);
option.value = getResources[i].children[0].innerHTML;
}
I want to clear all the data in the dropdown and default to the base HTML version with the --Select-- option, I'm currently using the following:
const empList = document.getElementById("employees-list");
while (empList.firstChild) {
empList.removeChild(empList.firstChild);
}
This works great but it clears all the data in the dropdown and throws the first value as the default which leads to the onchange function not executing and thus I have to pick another value and then back to the first one before it triggers. I don't know which will be easier, getting a workaround to letting the first value load immediately as the data populates the dropdown or change the loop so it removes everything except the default value. Any help would be greatly appreciated!

Related

How to dynamically add more elements to a dropdown list with vanilla JS

I can't use Jquery or anything else, just Vanilla Javascript.
My initial approach was to have an array in global scope storing every registered item and then using a foreach to append an <option> child to the <select>, but apparently this only creates one option and renames it
HTML
<label for="productList">Show Products</label>
<select name="products" id="productList">
</select>
JS
let productArray = [];
let dropdown = document.getElementById("productList");
dropdown.addEventListener("click", initializeList());
function initializeList(){
//initializing with an example
productArray.push("PROD1");
productArray.push("PROD2");
productArray.push("PROD3");
productArray.forEach( item => {
option = document.createElement("option");
option.text = item;
dropdown.appendChild(option)
});
}
Unfortunately, this is not a very efficient approach since I'd have to manually create a variable every time I want to add something. I am going to create a method where you just pass an option name and it gets added to the dropdown options. It seems that even though it's a forEach, every option being added is the same. How can I avoid this?
When you setup the addEventListener, you need to send the function itself, not the return value.
You also need to test whether the select list has already been created before running the initializeList function. That way you only initialize it once.
let productArray = [];
let dropdown = document.getElementById("productList");
dropdown.addEventListener("click", initializeList); // send initializeList not initializeList()
function initializeList() {
if (productArray.length != 0) { // Don't initialize more than once
return;
}
//initializing with an example
productArray.push("PROD1");
productArray.push("PROD2");
productArray.push("PROD3");
productArray.forEach(item => {
option = document.createElement("option");
option.text = item;
dropdown.appendChild(option)
});
}
<label for="productList">Show Products</label>
<select name="products" id="productList">
</select>

Do dependent dropdown in html using javascript with value and text

I have already a dependent dropdown list in my html form by using only javascript, but when my php script returns values these are just numbered by the position of the text in an array. I would like to have both Value and Text the same value
Here is what I have so far:
SCRIPT IN HEAD TAG:
var my_variable=[
["dropA_opt1","dropA_opt2",dropA_opt3"],
["dropB_opt1","dropB_opt2",dropB_opt3"],
["dropC_opt1","dropC_opt2",dropC_opt3"]
];
function variable(idx) {
var f=document.my_form;
f.drop_nr_2.length=null;
for(var i=0; i<my_variable[idx].length; i++) {
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], i);
}
}
SELECT for main DROPDOWN
<select name="drop_nr_1" onchange="my_variable(this.selectedIndex)">
<option value="" selected disabled></option>
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
SELECT for dependent DROPDOWN
<select name="drop_nr_2">
</select>
The code i have basically creates the options from the array index, but there is no value="" attribute. From that reason I am getting the array index back - but I need a value="same as the text".
In addition it would be nice to have always the first option in the 2nd dropdown selected and disabled with empty value (like in dropdown 1).
Much appreciate your help
When constructing <option> by using javascript object syntax.
var myOpt = new Option(lbl,val);
The first parameter is the label that user sees it having the second parameter is the value that will be used for this <option> internally.So just modify the constructor line a bit
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i]);
For second requirement add a condition for i===0 when it's true pass additional third parameter (wiz. selected) and make disabled property true
for(var i=0; i<my_variable[idx].length; i++) {
if(i===0){
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i],"selected");
f.drop_nr_2.options[i].disabled= true;
} else{
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i]);
}
}

Option value doesnt showup in dropdown - jquery

I am trying to add new options in a dropdown based on the other dropdown value.
the new added option doesnt appear in the dropdown on my custom webkit browser.
When I try to debug it the values are present in the dropdown, just it doesnt show up in the front end.
I have attached the code but its working in jsbin :(
When I click the empty dropdown and then click New button value doesnt show up but if I dont click the empty dropdown and click new button directly values appear normally.
https://jsbin.com/kikicuhabo/1/edit?html,css,js,output
It is a good practice to write HTML in lower case, and to close the tags.
If you want to use jQuery I recommend to select elements alway with the "$('')" instead of mixing with the "document. ... "
Since yours it is a custom browser I would try a solution in Vanilla JS.
function AddToCB(p_oCB, p_sText) {
var oSelect = document.querySelector(p_oCB);
var iNewLast = oSelect.length;
var sDisplay = p_sText + (iNewLast + 1);
var oNewItem = document.createElement('option');
oNewItem.innerHTML = sDisplay;
oNewItem.setAttribute('value', sDisplay)
oSelect.appendChild(oNewItem);
oSelect.selectedIndex = iNewLast;
return iNewLast;
}
function AddOption() {
var select = document.querySelector("#cmb");
var text = select.options[select.selectedIndex].value;
AddToCB('#list', text);
}
<select name="cmbColor" id="cmb">
<option>AA</option>
<option>BB</option>
<option>CC</option>
</select>
<input type="button" class="float-right" VALUE="New" onClick="AddOption()" >
<select name="list" id="list">
</select>

Javascript changing select box selected value not working properly

I am using javascript to programmatically add options to an html select box. When I add a new option, I am setting that option's .selected property to true so that it is the one that appears in the select box. When I do this, the innerHTML does not change to the new value, but when I click in the select box, I see the option I wanted selected has a checkmark next to it, indicating it is selected. Why isn't the value shown the correct value?
Here is my function that populates the select box options:
function printCartList(newCart){
// Check if newCart is null
newCart = newCart ? newCart : "a_new_cart_was_not_provided_12345abcde";
// set carts object from cookie if it exists, otherwise create a new one
if($.cookie("carts") != null){
carts = JSON.parse($.cookie("carts"));
}
else{
selectOption = new Object();
selectOption.value = "newuniquecartid12345abcde";
selectOption.html = "***New Cart***";
carts = new Object();
carts.size = 1;
carts.option = new Array();
carts.option[0] = selectOption;
}
// Get the select element
var select = document.getElementById("select_cart");
// Get the length of the select options list
var length = select.options.length;
// Remove all items from the select box
while(select.options.length > 0){
select.remove(0);
}
// If newCart was provided, create a new option and add it to the cart
if(newCart != "a_new_cart_was_not_provided_12345abcde"){
selectOption = new Object();
selectOption.value = newCart;
selectOption.html = newCart;
carts.option[carts.size] = selectOption;
carts.size++;
}
// Save the cart in a cookie
$.cookie("carts",JSON.stringify(carts));
// Add the options to the select box
for(var i = 0; i < carts.size; i++){
var opt = document.createElement('option');
opt.value = carts.option[i].value;
opt.innerHTML = carts.option[i].html;
if($.cookie("activeCart") == carts.option[i].value){
// Set the option to true if the cart is the active cart.
//*****I have tested this with an alert box showing the value of carts.option[i].value This is being called for the correct option*******
opt.selected = true;
}
select.appendChild(opt);
}
}
The new item is being added to the select box, and does have a checkmark next to it when viewing all the items in the select box, it just doesn't show the correct value in the select box.
Here is my html:
<form method="POST" name="cartSelectForm" action="home.php">
<select name="cartList" id="select_cart" data-mini="true" onchange="submitCartForm()" data-icon="false">
<option value="newuniquecartid1234567890">*** New Cart ***</option>
</select>
</form>
edit
I have discovered that jquery css is interfering with javascript filling the innerHTML of the select box. I am linking in: "http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css". Is there anyway to get around the jquery? I can't just remove the jquery css. That would break everything on my site, and I don't have time to redo it all.
Here is a jsfiddle of the problem: http://jsfiddle.net/RjXRB/1/
It's better to use angular way when creating select box - look here: http://docs.angularjs.org/api/ng.directive:select
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
</select>
If you have a reason to use the innerHtml approach, you should consider using Scope.apply or Scope.$digest as described in the docs.

Dropdown / Select Box Navigation with JavaScript ?

I want to ask quick question, i want to make a select drop down that when i choose one of the options the values of the other select drop down change ...
let's say i have select drop down called model that has the following
- Acura
- Aston martin
- Audi
I want when i choose (let's say ) Audi, in the type select drop down i find Audi type's only
- A3
- A5
- A4
I don't want to use AJAX calls, i just want to use javascript or jquery to filter the data
thanks guys
Like Shomz said,
Assuming the dropdowns look like this:
<!-- First dropdown. Make of car -->
<select name='Manufactor' id='make'>
<option value='null'>Select a Make</option>
<option value='Audi'>Audi</option>
<option value='BMW'>BMW</option>
<option value='Volvo'>Volvo</option>
</select>
<br />
<!-- Second dropdown. Model of car -->
<select name='Model' id='model'>
</select>
The javascript would look like this:
<script type='text/javascript'>
var model = ['','audi','bmw','volvo']; //Set makes
model[1] = ['A3', 'A5', 'A4']; // Set Audi models
model[2] = ['M3', 'M5', 'M6']; // Set BMW models
model[3] = ['C30', 'C70']; // Set Volvo models
var test = model[1][1];
function setModel(index) {
var modelDropdown = document.getElementById('model');
modelDropdown.options.length = null;
for(var i = 0; i < model[index].length; i++) {
modelDropdown.options[i] = new Option(model[index][i]);
}
}
window.onload = function() {
var makeDropdown = document.getElementById('make');
makeDropdown.onchange = function() {
setModel(this.selectedIndex);
}
}
</script>
Notice that the Models start at index 1 and not 0, because the first option is a blank Select Model option.
AJAX calls would still be the best solution, but if you don't want to use them, you can always manually create arrays for each of the main options, make an onchange event on the select element which would call the selected array and create another dropdown based on the elements of that array. Hope I didn't make it sound to complicated, since it isn't.
Here's a sample how to extract values with jQuery.

Categories

Resources