jQuery - Restore the removed select option - javascript

I have multiple dropdown menus with the same options. If one option was selected, other dropdown menus will not show the selected option. When I tried to reset the selected option, it did not restore the removed select option.
HTML part:
<select id="selectNumber" class="selectbox">
<option value="0">Choose a number</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="selectNumber2" class="selectbox">
<option value="0">Choose a number</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Javascript part:
$(".selectbox").change(function(){
var selectedIndex = $(this).index();
var myVal = $(this).val();
$(".selectbox").each(function(i){
if (selectedIndex != i){
$("option", this).each(function(){
if (myVal == $(this).val() && myVal != 0){
$(this).detach();
}else{
$(this).prepend();
//not work
}
});
}
});
});
the demo but not working
Thanks for your time.

This should do what you want
/* store options */
var $selects = $(".selectbox");
var $opts = $selects.first().children().clone();
$selects.change(function () {
var myVal = $(this).val();
if (myVal !='0') {
$selects.not(this).children('[value="'+myVal+'"]').remove();
}else{
var replaceVal=$(this).data('currVal');
$selects.not(this).append( $opts.filter( '[value="'+replaceVal+'"]').clone())
}
$(this).data('currVal', myVal);
});
DEMO http://jsfiddle.net/7Ssu7/8/
EDIT Version - keeps sort order
/* store options */
var $selects = $(".selectbox");
var $opts = $selects.first().children().clone();
$selects.change(function () {
/*create array of all selected values*/
var selectedValues=$selects.map(function(){
var val=$(this).val();
return val !=0? val :null;
}).get();
$selects.not(this).each(function(){
var $sel=$(this), myVal=$sel.val() ||0;
var $options=$opts.clone().filter(function(i){
var val=$(this).val();
return val==myVal || $.inArray(val, selectedValues) ==-1;
});
$sel.html( $options).val( myVal)
});
});
DEMO: http://jsfiddle.net/8uunN/1/

When you do a detach(), the object is removed and needs to be put into a "global" variable to save as a reference.
For your purpose, you can use .hide() and .show() as it retains the object in the list, without causing a DOM insertion or removal (so definitely better for performance).

Well, your current code is not work, because you are not store selected value in another dropdown list. Also, like others said, use hide and show instead of detach and prepend.
You can see my solution in jsfiddle (tested in firefox)

Related

Remove working on JQuery options, Hide does not?

Got this HTML:
<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
<option value="3">DC</option>
<option value="5">PL</option>
<option value="7">SA</option>
</select>
Iterating over the options with this javascript & jQuery:
var departmentDDL = $(row).find('[id*="DepartmentID_"] > option');
departmentDDL.each(function () {
if ($(this)[0].innerHTML != "SA") {
$(this).hide(); // this does not work
$(this).remove(); // this works
}
});
I'm trying to hide the options, not remove them. Why does one work and not the other?
You have an extra ( in your if, remove it, it will work but only in Chrome with a little buggy behavior.
var departmentDDL = $('[id*="DepartmentID_"] > option');
departmentDDL.each(function() {
if ($(this)[0].innerHTML != "SA") {
$(this).hide(); // this does not work
//$(this).remove(); // this works
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
<option value="3" >DC</option>
<option value="5">PL</option>
<option value="7">SA</option>
</select>
Note that hiding HTML options has several issues cross browser and won't give expected results in some browsers, for further details check How to hide a <option> in a <select> menu with CSS?
remove extra ( here if (($(this)[0] and it will work
var departmentDDL = $('[id*="DepartmentID_"] > option');
departmentDDL.each(function () {
if ($(this)[0].innerHTML != "SA") {
$(this).hide(); // this does not work
//$(this).remove(); // this works
}else{
$(this).parent().val($(this).val()).change();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
<option value="3">DC</option>
<option value="5">PL</option>
<option value="7">SA</option>
</select>
It selected in the else part

How do I make 2 select boxes to dismiss each other if they mach and automatically select the second option to not match?

How do I make 2 select boxes to dismiss each other if they match, by automatically selecting the second option?
I want it instead of "alert" to have a function that automatically changes one option to the second option on one of the select option boxes when they match.
If I can keep the alert and have it automatically change that would be ideal, but I accept if the alert can not be kept.
JavaScript
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script type='text/javascript'>
$(window).load(function(){
$(function () {
'use strict';
$('.OBSMatch').on('change', function (event) {
var selectedValue = $(event.currentTarget).val();
var matchedDropdowns = $('.OBSMatch').filter(function (index) {
return $(this).val() === selectedValue;
});
if (matchedDropdowns.length > 1) {
alert("OBS! You cannot use it, because it matches each other!")
}
})
})
});
</script>
HTML
<select name="LangF1" class="OBSMatch">
<option value="zh-CN">Chinese (Simplified)</option>
<option selected value="en">English</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="ru">Russian</option>
<option value="es">Spanish</option>
<option value="" disabled>—</option>
<option value="auto">Auto Detect</option>
</select>
<select name="LangF2" class="OBSMatch">
<option value="zh-CN">Chinese (Simplified)</option>
<option value="en">English</option>
<option selected value="fr">French</option>
<option value="de">German</option>
<option value="ru">Russian</option>
<option value="es">Spanish</option>
<option value="" disabled>—</option>
<option value="auto">Auto Detect</option>
</select>
Update: I added this update from the complete code because the former good answer is not working correctly because of this button that does Switches the option languages.
<script language="JavaScript">
function getSelectedOption( elem ) {
return elem.options[elem.selectedIndex].value;
}
function setSelectedOption( elem, value ) {
for (let i = 0; i < elem.options.length; i++) {
elem.options[i].selected = value === elem.options[i].value;
}
}
function swapByOptionValue( selector1, selector2 ) {
var elem1 = document.querySelector(selector1),
elem2 = document.querySelector(selector2),
selectedOption1 = getSelectedOption( elem1 ),
selectedOption2 = getSelectedOption( elem2 );
setSelectedOption( elem1, selectedOption2 );
setSelectedOption( elem2, selectedOption1 );
}
function swapBySelectedIndex( selector1, selector2 ) {
var elem1 = document.querySelector(selector1),
elem2 = document.querySelector(selector2),
selectedOption1 = elem1.selectedIndex;
elem1.selectedIndex = elem2.selectedIndex;
elem2.selectedIndex = selectedOption1;
}
</script>
<input type="button" id="SwitchLang" onClick="swapByOptionValue('select[name=\'LangF1\']', 'select[name=\'LangF2\']');" value=" Swap ▲▼ Language ">
What you are asking for is an UI which allows the user to put the UI into an illegal state, gives an alert, and attempts to make things legal.
This really doesn't make for a great UI.
If at all possible, the user should be prevented from putting the UI into an illegal state, then there's no need for an alert and no need to correct anything. Such a strategy is eminently possible here.
The basic rules are fairly simple. On change of either select menu :
the other menu's counterpart to this menu's current selection should be disabled.
the other menu's other options should be enabled.
any initially disabled options need to be protected from becoming enabled.
var $menus = $('.OBSMatch').on('change', function(event) {
$menus.not(this).find('option').filter(function(index, opt) {
return opt.value === event.target.value;
}).prop('disabled', true) // disable the other menu's option corresponding to this menu's selection
.siblings().not('._protected').prop('disabled', false); // enable the other menu's options except any that are protected.
});
$menus.find('option').filter(function(index, opt) {
return opt.disabled;
}).addClass('_protected'); // protect any initially disabled options from being enabled
$menus.trigger('change'); // initialize everything
DEMO
"Auto Detect" may need to be handled as a special case - I'm not sure.
Alternatively, for a set of 3+ select menus ...
DEMO
Edit:
The two menu's selections can be switched as follows :
function switch_(selector) {
var $menus = $(selector);
var values = $menus.map(function() {
return this.value;
}).get().reverse(); // reverse() swaps the two values
$menus.each(function(i, menu) {
$(this).val(values[i]); // implement the switch
}).trigger('change'); // re-initialize everything
}
// call
switch_('.OBSMatch');
// so, assuming you have a #switch element :
$('#switch').on('click', function() {
switch_('.OBSMatch');
});
DEMO
The function can't be named switch, which is a javascript reserved word; therefore switch_
Are you looking for something like this?
The key here is, on change:
Get the value of target element
Get the value of the related select
If values match, change the value of target element to the next option
$(window).load(function() {
$(function() {
'use strict';
$('.OBSMatch').on('change', function(event) {
var selectedVal = $(event.currentTarget).val();
var relatedId = $(this).attr('data-related');
var $otherSelect = $('#' + relatedId);
var otherVal = $otherSelect.val();
if (selectedVal === otherVal) {
$(this).val($(this).find('option:selected').next().val());
// alert("OBS! You cannot use it, because it matches each other!");
}
})
})
});
// UPDATE: Added code from updated question to test solution along with rest of code:
function getSelectedOption( elem ) {
return elem.options[elem.selectedIndex].value;
}
function setSelectedOption( elem, value ) {
for (let i = 0; i < elem.options.length; i++) {
elem.options[i].selected = value === elem.options[i].value;
}
}
function swapByOptionValue( selector1, selector2 ) {
var elem1 = document.querySelector(selector1),
elem2 = document.querySelector(selector2),
selectedOption1 = getSelectedOption( elem1 ),
selectedOption2 = getSelectedOption( elem2 );
setSelectedOption( elem1, selectedOption2 );
setSelectedOption( elem2, selectedOption1 );
}
function swapBySelectedIndex( selector1, selector2 ) {
var elem1 = document.querySelector(selector1),
elem2 = document.querySelector(selector2),
selectedOption1 = elem1.selectedIndex;
elem1.selectedIndex = elem2.selectedIndex;
elem2.selectedIndex = selectedOption1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="LangF1" class="OBSMatch" data-related="ddl2" id="ddl1">
<option value="zh-CN">Chinese (Simplified)</option>
<option selected value="en">English</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="ru">Russian</option>
<option value="es">Spanish</option>
<option value="disabled" disabled>—</option>
<option value="auto">Auto Detect</option>
</select>
<select name="LangF2" class="OBSMatch" data-related="ddl1" id="ddl2">
<option value="zh-CN">Chinese (Simplified)</option>
<option value="en">English</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="ru">Russian</option>
<option value="es">Spanish</option>
<option selected value="disabled" disabled>—</option>
<option value="auto">Auto Detect</option>
</select>
<!-- UPDATE: Added code from updated question to test solution along with rest of code: -->
<input type="button" id="SwitchLang" onClick="swapByOptionValue('select[name=\'LangF1\']', 'select[name=\'LangF2\']');" value=" Swap ▲▼ Language ">

How to get the value of option with attribute selected

I'm trying to get the value of the option which have the attribute "selected" to compare it to the current option selected.
function onChangeOption(opt) {
var update_value = opt.value;
var selectedValue = '???'; // get selected attribute
if (update_value != selectedValue) {
// Do some things
}
}
<select class="form-control" onchange="onChangeOption(this)">
<!-- I wanna got the content of option selected=selected-->
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
// save initial selected value to a variable
var initSelected = $('.form-control option:selected').val();
$('select').on('change', function() {
// check if the selected value is the same as the initial one was
if(this.value == initSelected) {
console.log('same values');
} else {
console.log('not same values');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Just add change event listener.And get the selected value.You can achieve comparision between selected value and changed value by maintaining an array.Like below.
values = []//creates an array
select = document.querySelector('#myselect');
values.unshift(select.value);
//console.log(values);
select.addEventListener('change',function(){
update_value = this.value;
console.log(this.value);
if (update_value != values[0]) {
// alert('Not matched');
console.log('Not matched');
}
else{
//alert('Matched');
console.log('Matched')
}
});
<select class="form-control" id="myselect">
<option selected="selected" value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
I think alexis actually wants something more like this:
function onChangeOption(opt) {
var update_value = opt.value;
var options = document.getElementsByTagName("option");
if (options[0].getAttribute("selected")=="selected") {
var selectedValue = options[0].value;
} else {
var selectedValue = options[1].value;
}
if (update_value != selectedValue) {
// If the selected option's value is not equal to the value of the option with the attribute "selected", then do... (this way, you can change the attribute to any of the options!)
console.log(selectedValue);
}
}
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Comment the result and if you need anything else. Glad to help.
You can always store previously selected values, if you want to access them somehow later on: working example.
HTML:
<select id="mySelect" class="form-control" onchange="onChangeOption(this)">
<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>
<p>Previous: <span id="prev"></span></p>
<p>Current: <span id="curr"></span></p>
JS:
var selectElem = document.getElementById("mySelect");
var prev = document.getElementById("prev");
var curr = document.getElementById("curr");
var allEverSelected = [ selectElem.value ];
selectElem.addEventListener("change", function(evt){
allEverSelected.push( this.value );
prev.innerHTML = allEverSelected[allEverSelected.length - 2];
curr.innerHTML = allEverSelected[allEverSelected.length - 1];
});
To access default value, just get the <select> value after DOM loads.
selected attribute on <option> tag exist only to make other than first <option> element inside <select> default option, i.e.:
<select>
<option value="1">1</option>
<option selected value="2">2</option>
</select>
Above select's default value is 2.
I think this is the one what you want. Try it.
function onChangeOption(opt) {
var update_value = opt.value;
console.log(update_value);
var selectedValue;// = '???'; // get selected attribute
// I think this is the one you want
//If you want to select the HTML element,
selectedValue=document.querySelector("option[value='"+update_value+"']");
console.log(selectedValue);
//
if (update_value != selectedValue) {
// Do some things
}
}
//onChangeOption(document.querySelector('form'));
function start(){
while(typeof document.querySelector('form')!=typeof {}){}
onChangeOption(document.querySelector('.form-control'));
}
<body onload="start()">
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<!-- I wanna got this -->
<option value="2">2</option>
</select></body>

Removing select items depending on selected items

I have two select elements with times 12:00 AM through 11:45 PM,
both selects have the same options inside including text and value. Is it possible for example say I select 1:00 PM on the first select to remove all the options before 1:00 PM on the second select? I know I can detect the change with jquery
$('#select1').change(function(){
// in here do something to remove previous selects
});
Any help would be appreciated it.
Here is another version of the same where we allow for the user to change his first selection and still filter the second select correctly
$(document).ready(function() {
var to_mins = function(x) {
var p = x.split(':').map(function(v) { return parseInt(v, 10); });
return (p[0] * 60) + p[1];
};
$('#second').data('options', $('#second').find('option').toArray());
$('#first').change(function() {
var val = to_mins(this.value);
console.log(val);
$('#second').empty();
$('#second').data('options').filter(function(v) {
return to_mins(v.value) > val;
}).map(function(v) {
$('#second').append(v.cloneNode(true));
});
});
});
Try
$('#select1').change(function(){
var $this = $(this);
var index = $('option:selected', $this).index();
$('#select2 option').show().filter(':lt(' + index + ')').hide();
})
Demo: Fiddle
try this
$('#select1').change(function(){
var value = $(this).val();
$("#selectId > option").each(function() {
if(value > this.value)
$("#selectId option[value=this.value]").remove();
});
});
But the values need to be in ascending order for select boxes
HTML:
<select id="select1">
<option value="1">11h00</option>
<option value="2">11h15</option>
<option value="3">11h30</option>
<option value="4">11h45</option>
<option value="5">12h00</option>
<option value="6">12h15</option>
<option value="7">12h30</option>
<option value="8">12h45</option>
<option value="9">13h00</option>
</select>
<select id="select2">
<option value="1">11h00</option>
<option value="2">11h15</option>
<option value="3">11h30</option>
<option value="4">11h45</option>
<option value="5">12h00</option>
<option value="6">12h15</option>
<option value="7">12h30</option>
<option value="8">12h45</option>
<option value="9">13h00</option>
</select>
JS:
$(document).ready( function(){
$('#select1').change(function(){
var val = $(this).find('option:selected').prop('value');
$('#select2').find('option').show().each(function(){
if( $(this).prop('value') <= val ){
$(this).hide();
}
else{
return false;
}
});
});
});

Changing the selected option of an HTML Select element

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
}
})

Categories

Resources