Here is the JS and HTML code:
function dateChange(){
var e = document.getElementById("trainingtype");
var str = e.options[e.selectedIndex].value;
var val = str;
if (val == "1"){
var x = document.getElementsByClassName("class1");
for(i=0; i<x.length; i++) {
x[i].style.display = "block";
}
var x = document.getElementsByClassName("class2");
for(i=0; i<x.length; i++) {
x[i].style.display = "none";
}
var x = document.getElementsByClassName("class3");
for(i=0; i<x.length; i++) {
x[i].style.display = "none";
}
document.getElementById("datepicker").value="Select Date and Place";
} else {
//another If else statement
}
}
<select name="item_name" id="trainingtype" onChange="dateChange()">
<option selected>Select training type</option>
<option value="Bike">Bike Riding</option>
<option value="Bucket">Bucket Washing</option>
<option value="Shoe">Shoe Tying</option>
</select>
<select name="datepicker" id="datepicker" onChange="amountChange(value)">
<option>Select Date and Place</option>
<option class="class1" value="1">1</option>
<option class="class2" value="2">2</option>
<option class="class3" value="3">3</option>
</select>
This code works perfectly in Chrome, Safari, and Firefox, but does not work in Microsoft Edge. In the console I get the error: SCRIPT5009: 'value' is undefined
How do I fix this?
The following line of JavaScript doesn't call the element you're expecting:
var e = document.getElementById("trainingtype");
This is calling the #trainingtype element, which is this:
<select name="item_name" id="trainingtype" onChange="dateChange()">
<option selected>Select training type</option>
<option value="Bike">Bike Riding</option>
<option value="Bucket">Bucket Washing</option>
<option value="Shoe">Shoe Tying</option>
</select>
You then go on to test the vlaue:
var str = e.options[e.selectedIndex].value;
var val = str;
if (val == "1") {
However, 1 is not similar to any value in the list of options. The original list of options has been replaced, but they weren't numbers. They were words/phrases.
It seems like, instead, you meant to call #datepicker (which has values like 1, 2, and 3). Otherwise, perhaps you unintentionally used the wrong value types in your first option list.
I want to output to multiple elements using JavaScript. The following example may show what i want.
<select id="leave" onchange="leaveChange()">
<option value="">Select</option>
<option value="150">EMS</option>
<option value="350">DHL</option>
<option value="200">UPS</option>
<option value="75">Ethiopia Postal</option>
</select>
<script>
function leaveChange() {
if (document.getElementById("leave").value == document.getElementById("leave").value){
document.getElementsByClassName("item_shipping")[0].innerHTML = document.getElementById("leave").value;
}
else{
document.getElementById("item_shipping").innerHTML = 0;
}
}
</script>
<div class="item_shipping"></div> //this is getting value
<div class="item_shipping"></div> //this i empty i want the same value?
The first div show the result but the second one is empty. How do I update both?
function leaveChange() {
var leaveValue = document.getElementById("leave").value;
var shippingItems = document.getElementsByClassName("item_shipping");
for (var i = 0; i < shippingItems.length; i++) {
if (leaveValue == leaveValue) // ??
shippingItems[i].innerHTML = leaveValue;
else
shippingItems[i].innerHTML = 0;
}
}
I have a number that is generated dynamically, and I would like to add this number of option elements to a select. I am thinking a for loop would be the best way to do this. Say my variable containing the number is var number. thanks for any help.
My starting HTML is:
<select id="test">
</select>
Using Javascript, I need something like this:
function selectOne() {
var select = document.getElementById('test');
// for loop goes here?
// e.select[0] = new Option(number); // do this n times with value also equaling number
}
So my resulting HTML needs to look like this, if the number = 6:
<select id="test">
<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>
<option value="6">6</option>
</select>
This builds n options :
function selectOne() {
var select = document.getElementById('test');
for (var i=0; i<n; i++) {
select.options[select.options.length] = new Option(i+1, i);
}
}
Demonstration
This should create your Options. And is backwards compatible for quite-a-many browsers supporting javascript
function selectOne() {
for (var selectEle = document.getElementById("test"), i = 1, o; i <= 6; i += 1) {
o = document.createElement("option");
o.value = i;
o.appendChild(document.createTextNode(i));
selectEle.appendChild(o);
/*
// As pointed out in the comments it can be done as such:
o = document.createElement("option");
o.value = o.text = i;
selectEle.appendChild(o);
*/
}
}
I have made same code in Javascript that will change options in drop-down list of cities when user changes state.
The problem with the code is that it won't work. I think that code is OK, but I am very new in JavaScript, so I can't see the error.
Can you please check my code and see where I made error. Thanks.
JavaScript:
function drzava_promjena() {
var obj_state = document.getElementById("id_drzava")
var index = obj_states.selectedIndex;
var value_state = obj_state.options[index].value;
towns = town_list[value_state];
var obj_town = document.getElementById("id_gradovi");
while (obj_town.options.length > 0) {
obj_town.remove(0);
}
var new_value;
for (var i = 0; i < towns.length; i++) {
new_value = document.createElement("option");
new_value.value = towns[i];
new_value.text = towns[i];
try {
obj_town.add(new_value);
} catch (e) {
obj_town.appendChild(new_value);
}
}
And this is HTML:
<select id="id_drzava" onchange="drzava_promjena(this);">
<option value="Austrija">Austrija</option>
<option value="Njemacka">Njemacka</option>
<option value="Slovenija">Slovenija</option>
<option value="Ceska">Ceska</option>
</select>
<br>
<select id="id_gradovi" onchange="">
<option value="0"></option>
</select>
<br>
<select id="id_uni" onchange="">
<option></option>
</select>
Try the following code. I've also put up a fiddle to demonstrate.
JavaScript:
var populateCities = function (country, target_id) {
var i = 0, options, cities, selection, target;
cities = {
"usa": {
"dallas": "dal",
"san francisco": "sf",
"houston": "hou"
},
"fr": {
"paris": "pr",
"la riche": "lr"
}
};
selection = country.options[country.selectedIndex].value;
target = document.getElementById(target_id);
target.options.length = 0;
if(selection !== 'none') {
options = cities[selection];
for(var city in options) {
target.options[i] = new Option(city, options[city]);
i++;
}
}
}
HTML:
<select id="country" onchange="populateCities(this, 'cities')">
<option selected value="none">Pick a country</option>
<option value="usa">USA</option>
<option value="fr">France</option>
</select>
<select id="cities"></select>
In my HTML, I have a <select> with three <option> elements. I want to use jQuery to check each option's value against a Javascript var. If one matches, I want to set the selected attribute of that option. How would I do that?
Vanilla JavaScript
Using plain old JavaScript:
var val = "Fish";
var sel = document.getElementById('sel');
document.getElementById('btn').onclick = function() {
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++) {
if (opt.value == val) {
sel.selectedIndex = j;
break;
}
}
}
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery
But if you really want to use jQuery:
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery - Using Value Attributes
In case your options have value attributes which differ from their text content and you want to select via text content:
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
Demo
But if you do have the above set up and want to select by value using jQuery, you can do as before:
var val = 3;
$('#sel').val(val);
Modern DOM
For the browsers that support document.querySelector and the HTMLOptionElement::selected property, this is a more succinct way of accomplishing this task:
var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
Demo
Knockout.js
<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
Demo
Polymer
<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
Demo
Angular 2
Note: this has not been updated for the final stable release.
<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor: function() {}});
ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
Demo
Vue 2
<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
Demo
None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.
The right way to select Alaska and have the select show the right item as selected using:
<select id="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
With jquery would be:
$('#state').val('AK').change();
You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:
document.getElementById('sel').value = 'bike';
DEMO
Markup
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
jQuery
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
Demo
I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.
Simplest code that worked is below:
var newValue1 = 'Mango'
var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;
Hope that helps someone. Best of luck.
Up vote if this helped you.
I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQuery you can do using core JS in simple steps:
Example
<select id="org_list">
<option value="23">IBM</option>
<option value="33">DELL</option>
<option value="25">SONY</option>
<option value="29">HP</option>
</select>
So you must know the value of the option to select.
function selectOrganization(id){
org_list=document.getElementById('org_list');
org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}
How to Use?
selectOrganization(25); //this will select SONY from option List
Your comments are welcome. :) AzmatHunzai.
Test this Demo
Selecting Option based on its value
var vals = [2,'c'];
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.val() == vals[n]){
$t.prop('selected', true);
return;
}
});
Selecting Option based on its text
var vals = ['Two','CCC']; // what we're looking for is different
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.text() == vals[n]){ // method used is different
$t.prop('selected', true);
return;
}
});
Supporting HTML
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select>
<option value=""></option>
<option value="a">AAA</option>
<option value="b">BBB</option>
<option value="c">CCC</option>
</select>
Excellent answers - here's the D3 version for anyone looking:
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<script>
d3.select('#sel').property('value', 'Fish');
</script>
After a lot of searching I tried #kzh on select list where I only know option inner text not value attribute,
this code based on select answer I used it to change select option according to current page urlon this format
http://www.example.com/index.php?u=Steve
<select id="sel">
<option>Joe</option>
<option>Steve</option>
<option>Jack</option>
</select>
<script>
var val = window.location.href.split('u=')[1]; // to filter ?u= query
var sel = document.getElementById('sel');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {
// search are based on text inside option Attr
if(opt.text == val) {
sel.selectedIndex = j;
break;
}
}
</script>
This will keeps url parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .
You just write the code
var theVal = 1;
$('#variable_id').val(theVal).trigger('change');
I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.
var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;
I hope this is useful.
selectElement is a html <select> element.
Increment the value:
selectElement.selectedIndex++
Decrement the value:
selectElement.selectedIndex--
var accHos = document.getElementById("accHos");
function showName(obj) {
accHos.selectedIndex = obj.selectedIndex;
}
div {
color: coral;
}
select {
margin-left: 20px;
margin-bottom: 8px;
min-width: 120px;
}
<div>Select Account Number:</div>
<select id="accNos" name="" onchange="showName(this);">
<option value="">Select Account</option>
<option value="">1052021</option>
<option value="">2052021</option>
<option value="">3052021</option>
<option value="">4052021</option>
<option value="">5052021</option>
</select>
<div>Account Holder Name:</div>
<select id="accHos" name="" disabled>
<option value="">--Name--</option>
<option value="">Suhan</option>
<option value="">Cesur</option>
<option value="">Hopper</option>
<option value="">Rachel</option>
<option value="">Arya</option>
</select>
<!-- Just for my referece -->
Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList missing .forEach():
NodeList.prototype.forEach = Array.prototype.forEach
Just:
var requiredValue = 'i-50332a31',
selectBox = document.querySelector('select')
selectBox.childNodes.forEach(function(element, index){
if ( element.value === requiredValue ) {
selectBox.selectedIndex = index
}
})