Set <select> element depending on another <select> element - javascript

I need a select element's options to change depending on the value of another.
<select id="first">
<option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
<option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
<option value="thisChanges">soDoesThis</option>
<option value="thisToo">andThis</option>
</select>
<script>
$("#first").on("change", function() {
<pseudo>
if #first == "1"
#second = {"this", "that", "the other"}
else if #first == "2"
#second = {"more", "even more", "yet another", "still more"}
</pseudo>
}
</script>
This is pretty much what I'm after (took me years to figure out how to completely replace the values of a select box), but the button click event doesn't even work. It was working a minute ago, although the for loop was not.
Obviously for my use case I would check if the select is clicked and retrieve its value with .val(), but I figured this button is easier for debugging.
JSFiddle
HTML:
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button>
Click me
</button>
JS:
var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
alert('click');
var sel = $('#sel');
alert('1');
sel.empty();
alert('2');
for (i = 0, i < list.length; i+2) {
$('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
}
alert('3');
});

I think you requirement similiar to the cascading dropdownlist, if i have understood correctly.
Ex jquery code:
$(document).ready(function () {
$("#state").prop("disabled", true);
$("#country").change(function () {
if ($("#country").val() != "Please select") {
var options = {};
options.url = "/home/getstates";
options.type = "POST";
options.data = JSON.stringify({ country: $("#country").val() });
options.dataType = "json";
options.contentType = "application/json";
options.success = function (states) {
$("#state").empty();
for (var i = 0; i < states.length; i++) {
$("#state").append("<option>" + states[i] + "</option>");
}
$("#state").prop("disabled", false);
};
options.error = function () { alert("Error retrieving states!"); };
$.ajax(options);
}
else {
$("#state").empty();
$("#state").prop("disabled", true);
}
});
});
Kindly refer this good article for the complete code:
http://www.binaryintellect.net/articles/b58fde6b-415e-454d-985b-d5dc4ad2fca8.aspx
Hope it will helps
Thanks
Karthik

Since you specified jQuery, I'll give you a jQuery answer! Grab the value and the text from the selected option, and append a new one to the select:
$(document).on('change', '#two', function() {
var option_to_add = $(this).find("option:selected").text();
var number_of_options = $('#two option').length
$('#one').append($('<option>', {
value: number_of_options,
text: option_to_add
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="one">
<option value="cash">Cash</option>
<option value="money">Money</option>
</select>
<select id="two">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
<option value="op1">Should be option 1: <a id="option1"></a></option>
</select> Should also be option 1:
<div id="option1"></div>
Based on your comments and changes to your post, if you just want to replace the options in a select element using a dummy array (or array of arrays,) you can do so the following way see code comments for details:
// dummy data array of arrays
var list = [
[11, "Eleven"],
[12, "Twelve"],
[13, "Thirteen"]
];
// click the button, replace the select contents
$('#btn').on('click', function() {
// build an array of option objects from an array of arrays
// see below
var opt_array = build_opt_array(list);
$('#sel').empty();
// add the new options
$(opt_array).each(function(index) {
$('#sel').append(opt_array[index]);
});
});
// helper function
// builds a new array of option html objects from
// an array of arrays
function build_opt_array(items) {
var opt_array = [];
$(items).each(function(index) {
var new_option = $('<option>', {
value: items[index][0],
text: items[index][1]
});
opt_array.push(new_option);
});
return opt_array;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button id="btn">
Click me
</button>

To get the text found in the first Select field, use the .text() function after using find(":selected") on your desired select field.
$("#two").focus(function() {
document.getElementById("option1").innerHTML = $("#one").find(":selected").text();
});

Related

Find duplicate values in pairs - select dropdown

I have pair of text boxes. I need to find duplicate pair values in my select dropdown.
JSFIDDLE example
txt12 txt12
txt2 txt1
txt3 txt3
txt4 txt5
txt12 txt12
In my example, txt12 select pair is duplicated. I could possibly find each duplicate values by considering each select dropdowns.
var selects = document.getElementsByTagName('select');
var values = [];
for(i=0;i<selects.length;i++) {
var select = selects[i];
if(values.indexOf(select.value)>-1) {
alert('duplicate - '+select.value); break;
}
else
values.push(select.value);
}
How is it possible to find duplicate pair of select dropdown values
You can use something like
function chkVal() {
var selects = document.getElementsByTagName('select');
var values = [];
for(i=0;i<selects.length;i++) {
var select = selects[i];
if(values.indexOf(select.value)>-1) {
alert('duplicate - '+select.value);
}
else
values.push(select.value);
}
}
You have to just remove the break in the if block as it is moving out of the for loop in the first loop when it find text12.
Refer to the fiddle : "http://jsfiddle.net/sL6ofchd/9/"
With jQuery, try something like this:
$('.check-value').on('click', function() {
var duplicates = $('select+br').prev().filter(function() {
return $(this).val() == $(this).prev().val();
});
console.log( duplicates.length );
});
$('.check-value').on('click', function() {
var duplicates = $('select+br').prev().filter(function() {
return $(this).val() == $(this).prev().val();
});
console.log( duplicates.length + ' duplicates' );
duplicates.each(function(i) {
console.log( i, this, $(this).prev()[0] );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="txt12">txt12</option>
</select> <select>
<option value="txt12">txt12</option>
</select><br><br>
<select>
<option value="txt2">txt2</option>
</select> <select>
<option value="txt1">txt1</option>
</select><br><br>
<select>
<option value="txt3">txt3</option>
</select> <select>
<option value="txt3">txt3</option>
</select><br><br>
<select>
<option value="txt12">txt12</option>
</select> <select>
<option value="txt12">txt12</option>
</select><br><br>
<input type="button" value="save" class="check-value">

Get element with a certain value, make it selected

I have a form with this disabled select element (I have disabled it with jquery)
<select class="select form-control" id="ifacility" name="facility">
<option value="" selected="selected">------</option>
<option value="1">Room 1</option>
<option value="2">Room 1</option>
<option value="3">Room 2</option>
<option value="4">Room 3</option>
</select>
I want to use Jquery to find an option with a name eg Room 2 and make it selected.
$(document).on('click', '.select-option', function() {
var room = $(this).attr('value') //This is what gives the 'Room 2'
//I want to select this room from the options and make it selected
});
You don't really need jQuery for this, so here's a plain-old JavaScript solution.
Declare this function:
function setOptionByValue(select, value){
var options = select.options;
for(var i = 0, len = options.length; i < len; i++){
if(options[i].textContent === value){
select.selectedIndex = i;
return true; //Return so it breaks the loop and also lets you know if the function found an option by that value
}
}
return false; //Just to let you know it didn't find any option with that value.
}
Use it like this:
setOptionByValue(document.getElementById('ifacility'), 'Room 2');
Demo
A jQuery solution using filter():
var room2 = $('#ifacility option').filter(function() {
return $(this).text() == 'Room 2';
});
// room2.val() = '3'
$('#ifacility').val(room2.val());
Fiddle
If you want to user jQuery to accomplish task, try this
$('#ifacility').find('option:contains("Room 2")').prop('selected', true);
It finds option by text and sets its selected attribute.

option is still visible in select after remove()

Hi all I have two select fields, on select field first if user select option value one or two then in select field of second all options are visible but if it select option two in first then option two want to remove from select id second. Following is my code:
<script type="text/javascript">
var index3,str;
</script>
<select id="first" onchange="chk();">
<option value = "one">one</option>
<option value = "two">two</option>
<option value = "three">three</option>
</select>
<select id="second">
<option value = "one">one</option>
<option value = "two">two</option>
<option value = "three">three</option>
</select>
<script type="text/javascript">
function chk()
{
index3 = document.getElementById("first");
str= index3.options[index3.selectedIndex].value;
alert("str:"+str);
if (str=="two")
{
$("#second option[value='two']").remove();
}
else
{
if ( $("#second option[value='two']").length == 0 )
{
$("#second").append('<option value="two">two</option>');
}
}
}
</script>
In fiddle it works fine here, But on mobile problem is: If I select option two from select id second, and then select option value two in first select id, then also option two is visible in second select id, if I click on second select id then only it removes. But in jsFiddle it works perfect. Any suggestion will be appreciated, Thanks in advance.
Here i have done complete bin for above issue. please go through demo link.
Demo http://codebins.com/bin/4ldqp7p
HTML
<select id="first">
<option value = "one">
one
</option>
<option value = "two">
two
</option>
<option value = "three">
three
</option>
</select>
<select id="second">
<option value = "one">
one
</option>
<option value = "two">
two
</option>
<option value = "three">
three
</option>
</select>
jQuery
$(function() {
$("#first").change(function() {
var optVal = $(this).val().trim();
if (optVal == "two") {
$("#second").find("option[value=" + optVal + "]").remove();
} else {
if ($("#second").find("option[value=two]").length <= 0) {
$("<option value=\"two\">two</option>").insertAfter($("#second").find("option[value='one']"));
}
}
});
});
Demo http://codebins.com/bin/4ldqp7p
check this Edit
$('#first').change(function() {
$("#second option[value='" + $(this).val() + "']").remove();
});
Your code looks a bit odd overall. If your intention is to remove the item from 'second' if it is selected in 'first', try this update: http://jsfiddle.net/NWbXt/58/
$(function() {
var first = $('#first'),
second = $('#second'),
removed;
first.change(function() {
var selected = first.val();
second.append(removed); //.. add back old option
removed = second.find('option[value="' + first.val() + '"]').remove();
}).trigger('change');
});​

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

How do I programmatically set the value of a select box element using JavaScript?

I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P

Categories

Resources