I have a dropdown with four option. I want to assign values to dropdown from javascript.
<select class="dropwdown-test" id="dropTest">
<option>Person 1</option>
<option>Person 2</option>
<option>Person 3</option>
<option>Person 4</option>
</select>
These are four variables that need to assigned to option values from a function() or function(response).
var p1 = 'john'
var p2 = 'marcus'
var p3 = 'anthony'
var p4 = 'aaron'
You can do something like below:
document.addEventListener('DOMContentLoaded', (event) => { // on DOM loaded
var p1 = 'john';
var p2 = 'marcus';
var p3 = 'anthony';
var p4 = 'aaron';
var list = [p1, p2, p3, p4]; // put the variables in a list
var select = document.getElementById("dropTest"); // get the select
var options = select.querySelectorAll("option"); // get it's options
options.forEach(function(el, i) {
if(list[i]) { // if list has element list[i]
el.value = list[i]; // assign option value to list[i]
// commenting out because OP wants only values assigned and not innerHTML
// el.innerHTML = list[i]; // assign option innerHTML to list[i]
}
});
})
<select class="dropwdown-test" id="dropTest">
<option>Person 1</option>
<option>Person 2</option>
<option>Person 3</option>
<option>Person 4</option>
</select>
Related
I have a select and a list of div elements like this:
<select name="select" id="select">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<button>submit</button>
<div id='list'>
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
</div>
I want to only show the div that has the h2's text that matches the selected value.
I'm trying the following JavaScript loop:
<script>
var select = document.getElementById('select');
var divItems = document.querySelectorAll('#table div');
var h2Items = document.querySelectorAll('#table div h2');
var button = document.querySelector('button');
button.addEventListener('click',function(){
var selectValue = select.value;
for(i=0; i < divItems.length; i++){
var h2Text = h2Items[i].innerHTML;
if (h2Text == selectValue){
divItems[i].display='block';
} else {
divItems[i].display='none';
}
}
});
But it doesn't work.
The console.log show that the h2's text and selected value are all correct,
but I don't know how to control the div's style.
Can somebody help me?
Thanks.
You need to specify that you are updating a style.
divItems[i].display='block'; should be divItems[i].style.display='block';
AND
divItems[i].display='none'; should be divItems[i].style.display='none';
Also, you are targeting #table, but you should be targeting #list since that is the id set on your main div.
Full JS:
<script>
var select = document.getElementById('select');
var divItems = document.querySelectorAll('#list div');
var h2Items = document.querySelectorAll('#list div h2');
var button = document.querySelector('button');
button.addEventListener('click',function(){
var selectValue = select.value;
for(i=0; i < divItems.length; i++){
var h2Text = h2Items[i].innerHTML;
if (h2Text == selectValue){
divItems[i].style.display='block';
} else {
divItems[i].style.display='none';
}
}
});
</script>
I have changed couple of things which I will explain below but first here is the solution which works as expected:
const select = document.getElementById('select');
const divItems = document.querySelectorAll('#list div'); // this was #table
const h2Items = document.querySelectorAll('#list div h2');
const button = document.querySelector('button');
button.addEventListener('click', function() {
const selectValue = select.value;
for(let i = 0; i < divItems.length; i++) {
if (h2Items[i].innerHTML === selectValue){
divItems[i].style = "display:block";
} else {
divItems[i].style = "display:none";
}
}
});
<select name="select" id="select">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<button>submit</button>
<div id="list">
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
<div><h2>a</h2>0</div>
<div><h2>b</h2>1</div>
<div><h2>c</h2>2</div>
<div><h2>d</h2>3</div>
</div>
Suggestions:
It is worth to check how HTMLElement.style works please find a link here.
Additionally learn the differences between var, let and const.
Last but not least differences between == and ===.
I hope this helps!
I've been following this guide on w3schools to dynamically change the elements of a dropdown select based off another dropdown select, as seen below:
The code to do this is as follows:
<!DOCTYPE html>
<html>
<body>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>
<script>
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("car");
var modelList = document.getElementById("carmodel");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
</body>
</html>
However, I noticed that for the second dropdown select, the element's values are numbered, and I was wondering how to change those values into text.
Eg. in the linked example the first select is as follows:
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
And if I set the value of the first select to Volvo, the second select is as follows:
<select id="carmodel">
<option value="1">V70</option>
<option value="2">XC60</option>
<option value="3">XC90</option>
</select>
What I would like to obtain compared to above:
<select id="carmodel">
<option value="V70">V70</option>
<option value="XC60">XC60</option>
<option value="XC90">XC90</option>
</select>
Replace var car = new Option(cars[i], i) with var car = new Option(cars[i], cars[i])
DEMO :
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("car");
var modelList = document.getElementById("carmodel");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], cars[i]);
modelList.options.add(car);
}
}
}
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>
You can do this easily using a PHP/MySQL/Ajax and store them in a database, however if you don't want to use any serverside programming, you can set a data-* global attribute for each of your option tags:
data-option="Car model name here"
Read more about "data-*" on W3Schools: https://www.w3schools.com/tags/att_global_data.asp
Here are two options for you:
Change the constructor:
var car = new Option(cars[i], cars[i]);
Or
var car = new Option(cars[i]);
car.value = cars[i];
Just after the constructor.
The problem you are facing is caused by the second argument in the constructor of the Option object, which gives the value of the option element.
I basically have this hard-coded:-
<select id="nr">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
It is supposed to select a value from an array, is there a way I can make a select without hard coding all those values? Preferably creating one with a loop with the length of my array in javascript or html?
Hope this helps you!
function addOptionValue(value) {
var option = document.createElement('option');
option.setAttribute('value', value);
option.innerHTML = value;
selectEl.appendChild(option);
}
var optionsArray = [1, 2, 3, 4, 5],
selectEl = document.getElementById('nr');
for (i in optionsArray) {
addOptionValue(optionsArray[i]);
}
<select id="nr"></select>
something like this?
var arr = [0,1,2,3,4,5];
var select_elem = document.getElementById("nr");
for (var i = 0; i < arr.length; i++){
var option = document.createElement("option");
option.value = arr[i];
option.text = arr[i];
select_elem.appendChild(option)
}
<select id="nr">
</select>
Jquery
$(function(){
for (i=1;i<=5;i++){
$("#nr").append($('<option></option>').val(i).html(i))
}
});
Javascript
<script>
for(var i=1; i<=5; i++){
var option = document.createElement("option");
option.value = i;
option.text = i;
document.getElementById('nr').appendChild(option);
}
/<script>
Demo
I have a select dropdownlist with 1 item selected at page load in html.
<select name = "options">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "3">Item3</option>
<option value = "4">Item4</option>
</select>
Now I want to capture new select option when user press shift and select another option such as "Item 3".
I have the following code to find all the selections in the list
var value = "";
for (var intLoop = 0; intLoop < Form.elements[index].length; intLoop++) {
if(Form.elements[index][intLoop].selected )
value = value + Form.elements[index][intLoop].value;
}
I can see the "Item 2" and "Item 3" are selected but i want to get capture "Item 3" only. Is it possible?
Here's code that will tell you what has been selected and what has been deselected http://jsfiddle.net/8dWzB/
It uses Array.prototype.indexOf, and it's not the fastest way to do it. But it should get you going in the right direction.
HTML
<select id="options" multiple="multiple">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "3">Item3</option>
<option value = "4">Item4</option>
</select>
JS
function getSelectedIndexes(select) {
var selected = [];
for (var i = 0; i < select.options.length; i++) {
if(select.options[i].selected ) {
selected.push(i);
}
}
return selected;
}
var select = document.getElementById("options");
var prevSelected = getSelectedIndexes(select);
select.onchange = function(e) {
var currentlySelected = getSelectedIndexes(this);
for (var i =0; i < currentlySelected.length; i++) {
if (prevSelected.indexOf(currentlySelected[i]) == -1) {
console.log("Added to selection ", this.options[currentlySelected[i]].text);
}
}
for (var i =0; i < prevSelected.length; i++) {
if (currentlySelected.indexOf(prevSelected[i]) == -1) {
console.log("Removed from selection ", this.options[prevSelected[i]].text);
}
}
prevSelected = currentlySelected;
};
If you really only want to know which item was last clicked, you can use the following code. I'll use jQuery so I can easily set a handler on all the option objects. Remember this won't work if you change the selection with the keyboard
$('option').click(function(e){
var parentNode = this.parentNode;
for (var i=0; i < this.parentNode.options.length; i++) {
if (parentNode.options[i] == this) {
console.log('Clicked item with index', i);
break;
}
}
});
You could check the value of the selected options before a change event (e.g. item 1 and 2 are selected) and then again after the event (e.g. item 1, 2 and 3 are selected), and compare the difference.
Here is an example.
Fiddle here: http://jsfiddle.net/FnAuz/4/
I modified your select to allow multiple selections since I take it that's the crux of the problem.
HTML:
<form id="my-form">
<select name = "options" id="options" multiple>
<option value = "val1">Item1</option>
<option value = "val2">Item2</option>
<option value = "val3">Item3</option>
<option value = "val4">Item4</option>
</select>
</form>
JS:
var oldValue = "";
document.getElementById('options').onchange = function() {
var myForm = document.getElementById ('my-form');
var value = "";
for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
if(myForm.elements[0][intLoop].selected) {
value = value + myForm.elements[0][intLoop].value;
}
}
for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
var optionVal = myForm.elements[0][intLoop].value;
if(myForm.elements[0][intLoop].selected && value.indexOf(optionVal) !== -1 && oldValue.indexOf(optionVal) === -1) {
console.log('Last clicked was ' + myForm.elements[0][intLoop].value)
}
}
oldValue = value;
};
EDIT: I just noticed that my example works when the user makes command/ctrl selections, but if they make a shift selection then ALL the new values will be counted as the 'last clicked item'. So my code would need some work to account for this scenario. I'm out of time, but hopefully my code is useful in its current state nevertheless!
Try this :
var e = document.getElementById("ID_of_Select_Element");
var _selectedValue= e.options[e.selectedIndex].value;
It started looking messy so I'm posting it as an answer:
<html>
<head>
<script type="text/javascript">
<!--
var value = '0';
document.getElementById('options').onchange = function() {
value = parseInt(value) + parseInt(this.value);
alert(value);
}
-->
</script>
</head>
<body>
<select name="options" id="options">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "4">Item3</option>
<option value = "8">Item4</option>
</select>
</body>
</html>
Edition for selecting multiple items:
well, if you want to accumulate items you can assign binary IDs to each product and then you can extract all the selected products from the total. for example, if the total is: 7 you can easily translate it to a binary string "111" which means they selected items 1,2,4. Sounds a bit crazy, I know, just an idea ;)
I've got the following select menu (jsFiddle):
<select>
<option value="volvo">Cars</option>
<option value="saab">------------</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Using Javascript, how would I re-sort the list alphabetically, excluding the first 2 options (Cars and -------), which must remain at the top? Thanks in advance for any help.
Being a purist, I would say that at no point was jQuery specifically mentioned or asked for, it may not be in use in this project for one reason or another. Here's an example using pure javascript.
function sortlist(){
var cl = document.getElementById('carlist');
var clTexts = new Array();
for(i = 2; i < cl.length; i++){
clTexts[i-2] =
cl.options[i].text.toUpperCase() + "," +
cl.options[i].text + "," +
cl.options[i].value + "," +
cl.options[i].selected;
}
clTexts.sort();
for(i = 2; i < cl.length; i++){
var parts = clTexts[i-2].split(',');
cl.options[i].text = parts[1];
cl.options[i].value = parts[2];
if(parts[3] == "true"){
cl.options[i].selected = true;
}else{
cl.options[i].selected = false;
}
}
}
sortlist();
http://jsfiddle.net/GAYvL/7/
Updated to be case neutral.
My first approach was similar to Koolinc's, using Array.prototype.slice to convert the <select> element's children NodeList to an array. However, this doesn't work in Internet Explorer 8 and lower so I changed it to extract, sort and then re-insert:
var sel = document.getElementsByTagName("select")[0],
opts = [];
// Extract the elements into an array
for (var i=sel.options.length-1; i >= 2; i--)
opts.push(sel.removeChild(sel.options[i]));
// Sort them
opts.sort(function (a, b) {
return a.innerHTML.localeCompare(b.innerHTML);
});
// Put them back into the <select>
while(opts.length)
sel.appendChild(opts.shift());
Working demo: http://jsfiddle.net/3YjNR/2/
This is just a more generic answser based on #Jeff Parker's one!
function sortSelect(select, startAt) {
if(typeof startAt === 'undefined') {
startAt = 0;
}
var texts = [];
for(var i = startAt; i < select.length; i++) {
texts[i] = [
select.options[i].text.toUpperCase(),
select.options[i].text,
select.options[i].value
].join('|');
}
texts.sort();
texts.forEach(function(text, index) {
var parts = text.split('|');
select.options[startAt + index].text = parts[1];
select.options[startAt + index].value = parts[2];
});
}
I have also created a fiddle; http://jsfiddle.net/4u86B/1/
I would start by giving a class name to all of the entries I want to sort, and giving and ID to the select:
<select id="sortableCars">
<option value="volvo">Cars</option>
<option class="sortMe" value="saab">------------</option>
<option class="sortMe" value="volvo">Volvo</option>
<option class="sortMe" value="saab">Saab</option>
<option class="sortMe" value="mercedes">Mercedes</option>
<option class="sortMe" value="audi">Audi</option>
</select>
as for the javascript
var mylist = $('#sortableCars');
var listitems = mylist.children('option.sortMe').get();
listitems.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });