Javascript changing select box selected value not working properly - javascript

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.

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>

JavaScript Reset a dropdown to it's default option

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!

Apply appendChild() with more than one option using only Javascript

I have a button that when pushed, it creates a new row. That row consists of selects,texts, and cells. My select box, when created has a default option 't'. How do I list multiple options without using html?
I tried to create a new textnode and when I do the appendChild for both options, I get them both on the same line. I need the second variable 'u' to be an entirely new option. Any help is most appreciated.
HTML
<button onclick="AddRow()"></button>
Javascript
function addRow(){
var optionObject = {};
var table=document.getElementById('table2'),tr,input,row,cell
tr=document.createElement('tr');
tr.setAttribute("class","rows");
tr.id = "AddedRow";
field = document.createElement("select");// this is where the select box is
var z = document.createElement("option"); //this is to create an option for the select box
z.setAttribute("value", "Choose"); // this is to give it a default value
var t = document.createTextNode("Select a Current Job");// this is to give it a default field name
var u = document.createTextNode("Select yoyo");// this is to give it a default field name
z.appendChild(t);// append the default field name to the option
z.appendChild(u);// append the default field name to the option
field.appendChild(z);// append the option to the select box
field.setAttribute("id","jobSelector");
//field.setAttribute("class","celltimes5a");
field.setAttribute("class","celltimesSelect");
var jobCol=document.createElement('td');
jobCol.setAttribute("class","celltimes5c");
tr.appendChild(field);
tr.appendChild(jobCol);
td=document.createElement('td');
td.setAttribute("class",'celltimes4c');
td.id = "row14total";
tr.appendChild(td);
table.appendChild(tr);
}
needed to create a another new option and append it as well
var z = document.createElement("option"); //this is to create an option for the select box
z.setAttribute("value", "Choose"); // this is to give it a default value
var w = document.createElement("option"); //this is to create an option for the select box
w.setAttribute("value", "Choose"); // this is to give it a default value
var t = document.createTextNode("Select a Current Job");// this is to give it a default field name
var u = document.createTextNode("Select yoyo");// this is to give it a default field name
z.appendChild(t);// append the default field name to the option
w.appendChild(u);// append the default field name to the option
field.appendChild(z);// append the option to the select box
field.appendChild(w);// append the option to the select box

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>

how to populate year values in dropdownlist using javascript [duplicate]

This question already has answers here:
Add item to dropdown list in HTML using JavaScript
(5 answers)
Closed 8 years ago.
i need to populate year in second dropdownlist on selecting value from first dropdown.And the year range is between 1900 to 2050
can anyone help?
First, create a select element. So in your HTML document,
<select id="year">
<option value="-1"> </option>
</select>
There is an empty option if the user doesn't want to fill it in. Feel free to give it an another value or another text like "please choose a year". The reason behind it is that if the user has disabled javascript, the years won't be appended. You will end with an empty select box.
Then use a script to add more option elements to fill it with years.
// get selectbox
var selectBox = document.getElementById('year');
// loop through years
for (var i = 2050; i >= 1900; i--) {
// create option element
var option = document.createElement('option');
// add value and text name
option.value = i;
option.innerHTML = i;
// add the option element to the selectbox
selectBox.appendChild(option);
}
Please ensure that the parameter at getElementById has the same id as the HTML select element.
A needless One Liner: (DEMO)
$((new Array(150) + "").split(",").map(function (i,j) {return $("<option>").append(j + 1900)[0];})).appendTo($("select"));
Expanded:
var option = function (i,j) {return $("<option>").append(j + 1900);};
var options = (new Array(150) + "").split(",").map(option);
$("select").append(options);
I have created jsfiddle Please look
I have attached change event to first combo box and according to its value populating 2nd combo value.
You can do whatever you want inside function
$("#s1").on("change", function(){
var value = $(":selected", this).val();
if(value == 'a'){
$("#s2").val('2000');
}else{
$("#s2").val('2010');
}
})
Just create a for loop that starts at 1900 and ends at 2050 (or the other side), and append options to the dropdownlist:
<select id="myDDL"></select>
var i=0;
for(i=1900;i<=2500;i++)
{
$("#myDDL").append("<option value='"+i+"'>"+i+"</option>")
}

Categories

Resources