Use URL Parameter to Preselect Option by Label not Value - javascript

How can I pass the label, not the option, to have javascript preselect from a dropdown?
For example, let's say the URL is page.html?option=name3
and in the form there's a select like this
<select id="select-box">
<option value="1">Name1</option>
<option value="2">Name2</option>
<option value="3">Name3</option>
<option value="4">Name4</option>
</select>
In this example Name3 and 3 are different.
What javascript could be used to preselect the option whose text contents match that of the URL parameter above?

Read the query param from the current page's URL: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
const optionParam = new URLSearchParams(window.location.search).get('option'); // "Name3"
and than set the Select value to the option which textContent matches
// const optionParam = new URLSearchParams(window.location.search).get('option');
const optionParam = "Name3"; // (PS: Use the above one instead, this is for demo)
const sel = document.getElementById("select-box");
const opt = [...sel.options].find(op => op.textContent===optionParam);
if (opt) sel.value = opt.value;
<select id="select-box">
<option value="1">Name1</option>
<option value="2">Name2</option>
<option value="3">Name3</option>
<option value="4">Name4</option>
</select>

You need to set the selectedIndex of your element using javascript as follows. First, parse the url to get the desired query option. You can use window.location API to get the url and do your operations on it. Then, iterate through each option of your select element and determine a good match using some logic.
I hope this helps.
<select id="select-box">
<option value="1">Name1</option>
<option value="2">Name2</option>
<option value="3">Name3</option>
<option value="4">Name4</option>
</select>
<script>
// to get option we use some parsing:
function getOption(url) {
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
if (queryString){
var optionString = queryString.split('=')[1];
// returns string for options if specified.
return optionString;
}
// return null otherwise.
return null;
}
var e = document.getElementById("select-box");
// var o = getOption(window.location.href);
// var o = getOption(document.url) // does not work for Firefox
// replace this with one of the lines above for dynamic solution
var o = getOption('page.html?option=name3');
if(o) {
for(var i=0; i<e.options.length; i++) {
if(o === e.options[i].innerHTML.toLowerCase()){
// be careful about case sensitivity and try to come up
// with your own logic on how you validate this,
document.getElementById("select-box").selectedIndex = i;
}
}
}else {
// if no option default to 0
document.getElementById("select-box").selectedIndex = 0;
}
</script>

Related

Multiple selection on dropdown list not working [duplicate]

I have a <select> element with the multiple attribute. How can I get this element's selected values using JavaScript?
Here's what I'm trying:
function loopSelected() {
var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
var selectedArray = new Array();
var selObj = document.getElementById('slct');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}
No jQuery:
// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
Quick example:
<select multiple>
<option>opt 1 text
<option value="opt 2 value">opt 2 text
</select>
<button onclick="
var el = document.getElementsByTagName('select')[0];
alert(getSelectValues(el));
">Show selected values</button>
With jQuery, the usual way:
var values = $('#select-meal-type').val();
From the docs:
In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option;
Actually, I found the best, most-succinct, fastest, and most-compatible way using pure JavaScript (assuming you don't need to fully support IE lte 8) is the following:
var values = Array.prototype.slice.call(document.querySelectorAll('#select-meal-type option:checked'),0).map(function(v,i,a) {
return v.value;
});
UPDATE (2017-02-14):
An even more succinct way using ES6/ES2015 (for the browsers that support it):
const selected = document.querySelectorAll('#select-meal-type option:checked');
const values = Array.from(selected).map(el => el.value);
You can use selectedOptions property
var options = document.getElementById('select-meal-type').selectedOptions;
var values = Array.from(options).map(({ value }) => value);
console.log(values);
<select id="select-meal-type" multiple="multiple">
<option value="1">Breakfast</option>
<option value="2" selected>Lunch</option>
<option value="3">Dinner</option>
<option value="4" selected>Snacks</option>
<option value="5">Dessert</option>
</select>
ES6
[...select.options].filter(option => option.selected).map(option => option.value)
Where select is a reference to the <select> element.
To break it down:
[...select.options] takes the Array-like list of options and destructures it so that we can use Array.prototype methods on it (Edit: also consider using Array.from())
filter(...) reduces the options to only the ones that are selected
map(...) converts the raw <option> elements into their respective values
If you wanna go the modern way, you can do this:
const selectedOpts = [...field.options].filter(x => x.selected);
The ... operator maps iterable (HTMLOptionsCollection) to the array.
If you're just interested in the values, you can add a map() call:
const selectedValues = [...field.options]
.filter(x => x.selected)
.map(x => x.value);
Check-it Out:
HTML:
<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server" SelectionMode="Multiple" Width="100px">
<asp:ListItem Text="Raj" Value="1"></asp:ListItem>
<asp:ListItem Text="Karan" Value="2"></asp:ListItem>
<asp:ListItem Text="Riya" Value="3"></asp:ListItem>
<asp:ListItem Text="Aman" Value="4"></asp:ListItem>
<asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>
JQUERY:
$("#aSelect").click(function(){
var selectedValues = [];
$("#lstSelect :selected").each(function(){
selectedValues.push($(this).val());
});
alert(selectedValues);
return false;
});
CLICK HERE TO SEE THE DEMO
First, use Array.from to convert the HTMLCollection object to an array.
let selectElement = document.getElementById('categorySelect')
let selectedValues = Array.from(selectElement.selectedOptions)
.map(option => option.value) // make sure you know what '.map' does
// you could also do: selectElement.options
suppose the multiSelect is the Multiple-Select-Element, just use its selectedOptions Property:
//show all selected options in the console:
for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
console.log( multiSelect.selectedOptions[i].value);
}
$('#select-meal-type :selected') will contain an array of all of the selected items.
$('#select-meal-type option:selected').each(function() {
alert($(this).val());
});
​
Pretty much the same as already suggested but a bit different. About as much code as jQuery in Vanilla JS:
selected = Array.prototype.filter.apply(
select.options, [
function(o) {
return o.selected;
}
]
);
It seems to be faster than a loop in IE, FF and Safari. I find it interesting that it's slower in Chrome and Opera.
Another approach would be using selectors:
selected = Array.prototype.map.apply(
select.querySelectorAll('option[selected="selected"]'),
[function (o) { return o.value; }]
);
Update October 2019
The following should work "stand-alone" on all modern browsers without any dependencies or transpilation.
<!-- display a pop-up with the selected values from the <select> element -->
<script>
const showSelectedOptions = options => alert(
[...options].filter(o => o.selected).map(o => o.value)
)
</script>
<select multiple onchange="showSelectedOptions(this.options)">
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
</select>
If you need to respond to changes, you can try this:
document.getElementById('select-meal-type').addEventListener('change', function(e) {
let values = [].slice.call(e.target.selectedOptions).map(a => a.value));
})
The [].slice.call(e.target.selectedOptions) is needed because e.target.selectedOptions returns a HTMLCollection, not an Array. That call converts it to Array so that we can then apply the map function, which extract the values.
Check this:
HTML:
<select id="test" multiple>
<option value="red" selected>Red</option>
<option value="rock" selected>Rock</option>
<option value="sun">Sun</option>
</select>
Javascript one line code
Array.from(document.getElementById("test").options).filter(option => option.selected).map(option => option.value);
if you want as you expressed with breaks after each value;
$('#select-meal-type').change(function(){
var meals = $(this).val();
var selectedmeals = meals.join(", "); // there is a break after comma
alert (selectedmeals); // just for testing what will be printed
})
Try this:
$('#select-meal-type').change(function(){
var arr = $(this).val()
});
Demo
$('#select-meal-type').change(function(){
var arr = $(this).val();
console.log(arr)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-meal-type" multiple="multiple">
<option value="1">Breakfast</option>
<option value="2">Lunch</option>
<option value="3">Dinner</option>
<option value="4">Snacks</option>
<option value="5">Dessert</option>
</select>
fiddle
Here is an ES6 implementation:
value = Array(...el.options).reduce((acc, option) => {
if (option.selected === true) {
acc.push(option.value);
}
return acc;
}, []);
Building on Rick Viscomi's answer, try using the HTML Select Element's selectedOptions property:
let txtSelectedValuesObj = document.getElementById('txtSelectedValues');
[...txtSelectedValuesObj.selectedOptions].map(option => option.value);
In detail,
selectedOptions returns a list of selected items.
Specifically, it returns a read-only HTMLCollection containing HTMLOptionElements.
... is spread syntax. It expands the HTMLCollection's elements.
[...] creates a mutable Array object from these elements, giving you an array of HTMLOptionElements.
map() replaces each HTMLObjectElement in the array (here called option) with its value (option.value).
Dense, but it seems to work.
Watch out, selectedOptions isn't supported by IE!
You can get as an array the values from the <select> at the submit of the form as this example :
const form = document.getElementById('form-upload');
form.addEventListener('change', (e) => {
const formData = new FormData(form);
const selectValue = formData.getAll('pets');
console.log(selectValue);
})
<form id="form-upload">
<select name="pets" multiple id="pet-select">
<option value="">--Please choose an option--</option>
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="hamster">Hamster</option>
<option value="parrot">Parrot</option>
<option value="spider">Spider</option>
<option value="goldfish">Goldfish</option>
</select>
</form>
Something like the following would be my choice:
let selectElement = document.getElementById('categorySelect');
let selectedOptions = selectElement.selectedOptions || [].filter.call(selectedElement.options, option => option.selected);
let selectedValues = [].map.call(selectedOptions, option => option.value);
It's short, it's fast on modern browsers, and we don't care whether it's fast or not on 1% market share browsers.
Note, selectedOptions has wonky behavior on some browsers from around 5 years ago, so a user agent sniff isn't totally out of line here.
You Can try this script
<!DOCTYPE html>
<html>
<script>
function getMultipleSelectedValue()
{
var x=document.getElementById("alpha");
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
alert(x.options[i].value);
}
}
}
</script>
</head>
<body>
<select multiple="multiple" id="alpha">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
<input type="button" value="Submit" onclick="getMultipleSelectedValue()"/>
</body>
</html>
You can use [].reduce for a more compact implementation of RobG's approach:
var getSelectedValues = function(selectElement) {
return [].reduce.call(selectElement.options, function(result, option) {
if (option.selected) result.push(option.value);
return result;
}, []);
};
My template helper looks like this:
'submit #update': function(event) {
event.preventDefault();
var obj_opts = event.target.tags.selectedOptions; //returns HTMLCollection
var array_opts = Object.values(obj_opts); //convert to array
var stray = array_opts.map((o)=> o.text ); //to filter your bits: text, value or selected
//do stuff
}
Same as the earlier answer but using underscore.js.
function getSelectValues(select) {
return _.map(_.filter(select.options, function(opt) {
return opt.selected; }), function(opt) {
return opt.value || opt.text; });
}
Works everywhere without jquery:
var getSelectValues = function (select) {
var ret = [];
// fast but not universally supported
if (select.selectedOptions != undefined) {
for (var i=0; i < select.selectedOptions.length; i++) {
ret.push(select.selectedOptions[i].value);
}
// compatible, but can be painfully slow
} else {
for (var i=0; i < select.options.length; i++) {
if (select.options[i].selected) {
ret.push(select.options[i].value);
}
}
}
return ret;
};
Here ya go.
const arr = Array.from(el.features.selectedOptions) //get array from selectedOptions property
const list = []
arr.forEach(item => list.push(item.value)) //push each item to empty array
console.log(list)
$('#application_student_groups option:selected').toArray().map(item => item.value)
You can create your own function like this and use it everywhere
Pure JS
/**
* Get values from multiple select input field
* #param {string} selectId - the HTML select id of the select field
**/
function getMultiSelectValues(selectId) {
// get the options of select field which will be HTMLCollection
// remember HtmlCollection and not an array. You can always enhance the code by
// verifying if the provided select is valid or not
var options = document.getElementById(selectId).options;
var values = [];
// since options are HtmlCollection, we convert it into array to use map function on it
Array.from(options).map(function(option) {
option.selected ? values.push(option.value) : null
})
return values;
}
you can get the same result using jQuery in a single line
$('#select_field_id').val()
and this will return the array of values of well.

two html select conflict

I have two html select element that the second one is disabled at first and only become enable if user choose one option from first select. consider we have 2 options in first select -> a , b if user choose a : in the second select options should be : a1,a2 if user choose b : in the second select options should be : b1,b2 ... I dont know what am i doing wrong that these two select options have conflict with each other !!!
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option value="a"> a </option>
<option value="b"> b </option>
</select>
<select id="sub-category" required disabled> </select>
<!-- empty select -->
<script>
document.getElementById("main-category").onchange = function() {
document.getElementById('sub-category').disabled = false;
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "a1";
opt0.innerHTML = "a1";
opt1.value = "a2";
opt1.innerHTML = "a2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
} else if (this.value == 'b') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) { //check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "b1";
opt0.innerHTML = "b1";
opt1.value = "b2";
opt1.innerHTML = "b2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
}
};
</script>
All you need to do is clear out the previous entries in the second drop down every time a selection is made in the first one.
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option value="a"> a </option>
<option value="b"> b </option>
</select>
<select id="sub-category" required disabled> </select>
<!-- empty select -->
<script>
document.getElementById("main-category").onchange = function() {
// Clear out the second list before adding new items to it
document.getElementById('sub-category').innerHTML = "";
// *******************************************************
document.getElementById('sub-category').disabled = false;
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "a1";
opt0.innerHTML = "a1";
opt1.value = "a2";
opt1.innerHTML = "a2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
} else if (this.value == 'b') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) { //check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "b1";
opt0.innerHTML = "b1";
opt1.value = "b2";
opt1.innerHTML = "b2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
}
};
</script>
But, beyond that, your code needs to be cleaned up quite a bit because you shouldn't be scanning the document for the element you want to work with over and over again when you've already found it before. That's extremely wasteful.
Also, .innerHTML is for passing strings that contain HTML so that the HTML parser can parse the string and update the DOM accordingly. You are just setting plain strings with no HTML in them, so you should be using .textContent instead, which doesn't invoke the HTML parser and is more efficient.
Next (just FYI), if you want the value of an option to be the same as the text that is displayed to the user, you don't need to set a value for that option. The value is the contents of the option element by default.
Really, the entire operation can be made so much simpler by simply making new options in list2 based on the first letter of the option chosen in list1.
// Get references to the elements you'll be working with just once:
var list1 = document.getElementById("main-category");
var list2 = document.getElementById('sub-category');
list1.onchange = function() {
list2.disabled = false;
var newHTML = ""; // A string that will contain the new HTML for the second list
// Loop the amount of times we find <option> elements in list one, but start
// at the second one to account for the first one, which isn't really a true choice
for(var i = 1; i < list1.querySelectorAll("option").length; i++){
// Build up a string that the new option should be made from using the
// first character from the option found in list 1
newHTML += '<option>' + list1.value.substr(0,1) + i + '</option>';
}
// By setting a new value for .innerHTML, the old values get thrown out.
list2.innerHTML = newHTML;
};
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option>a</option>
<option>b</option>
</select>
<select id="sub-category" required disabled> </select>

Javascript/jQuery: Set Values (Selection) in a multiple Select

I have a multiple select:
<select name='strings' id="strings" multiple style="width:100px;">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On">On</option>
</select>
I load data from my database. Then I have a string like this:
var values="Test,Prof,Off";
How can I set this Values in the multiple select? Already tried change the string in an array and put it as value in the multiple, but doesnt work...!
Can someone help me with this? THANKS!!!
Iterate through the loop using the value in a dynamic selector that utilizes the attribute selector.
var values="Test,Prof,Off";
$.each(values.split(","), function(i,e){
$("#strings option[value='" + e + "']").prop("selected", true);
});
Working Example http://jsfiddle.net/McddQ/1/
in jQuery:
$("#strings").val(["Test", "Prof", "Off"]);
or in pure JavaScript:
var element = document.getElementById('strings');
var values = ["Test", "Prof", "Off"];
for (var i = 0; i < element.options.length; i++) {
element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}
jQuery does significant abstraction here.
Just provide the jQuery val function with an array of values:
var values = "Test,Prof,Off";
$('#strings').val(values.split(','));
And to get the selected values in the same format:
values = $('#strings').val();
Pure JavaScript ES6 solution
Catch every option with a querySelectorAll function and split the values string.
Use Array#forEach to iterate over every element from the values array.
Use Array#find to find the option matching given value.
Set it's selected attribute to true.
Note: Array#from transforms an array-like object into an array and then you are able to use Array.prototype functions on it, like find or map.
var values = "Test,Prof,Off",
options = Array.from(document.querySelectorAll('#strings option'));
values.split(',').forEach(function(v) {
options.find(c => c.value == v).selected = true;
});
<select name='strings' id="strings" multiple style="width:100px;">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On">On</option>
</select>
var groups = ["Test", "Prof","Off"];
$('#fruits option').filter(function() {
return groups.indexOf($(this).text()) > -1; //Options text exists in array
}).prop('selected', true); //Set selected
Basically do a values.split(',') and then loop through the resulting array and set the Select.
Pure JavaScript ES5 solution
For some reason you don't use jQuery nor ES6? This might help you:
var values = "Test,Prof,Off";
var splitValues = values.split(',');
var multi = document.getElementById('strings');
multi.value = null; // Reset pre-selected options (just in case)
var multiLen = multi.options.length;
for (var i = 0; i < multiLen; i++) {
if (splitValues.indexOf(multi.options[i].value) >= 0) {
multi.options[i].selected = true;
}
}
<select name='strings' id="strings" multiple style="width:100px;">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On" selected>On</option>
</select>
Use this:
$('#demo').multiselect('select', value);
For multiple values just use a loop
For more properties this page is very good
this is error in some answers for replace |
var mystring = "this|is|a|test";
mystring = mystring.replace(/|/g, "");
alert(mystring);
this correction is correct but the | In the end it should look like this \|
var mystring = "this|is|a|test";
mystring = mystring.replace(/\|/g, "");
alert(mystring);

wrong html output from the javascript

I wrote a script for populating a selectbox with a bunch of options.
Initially the data is in the form of string of a format "key=value;key2=value2;etc...":
//split the string to distinguish between different options to populate a selectbox with
var values = data.split(';');
//reset the length of the selectbox to be populated
document.getElementById(child).options.length = 0;
//create first default option
document.getElementById(child).options[0] = new Option('all', '0');
for(var i = 0; i < values.length; i++){
//check for and remove unnecessary characters
values[i].replace(/\s+/g, '');
//split the option to get the key and value separately
var options = values[i].split('=');
if(!isEmpty(options[0]) && !isEmpty(options[1])){
//insert a new element to the selectbox
document.getElementById(child).options[i+1] = new Option(options[1], options[0]);
}
}
The example above populates a selectbox with the given html output:
<option value="0">all</option>
<option value="
7">Bermuda</option>
<option value="10">British Virgin Islands</option>
<option value="15">Cayman Islands</option>
<option value="42">Jamaica</option>
<option value="74">St. Lucia</option>
<option value="79">Trinidad Tobago</option>
As you can notice above the second option in the selectbox has a corrupted string value. I need to fix that value because because of that cake cannot save this value properly.
If you have any other questions please ask.
You should try to trim values:
document.getElementById(child).options[i+1] = new Option(
options[1].replace(/^\s+|\s+$/g, ''),
options[0].replace(/^\s+|\s+$/g, '')
);
or if you are using jquery:
document.getElementById(child).options[i+1] = new Option(
$.trim(options[1]),
$.trim(options[0])
);
also you should look close on this fragment:
values[i].replace(/\s+/g, '');
because probably it doesn't do what you want. First, it removes all whitespaces from string so "New York City" will become "NewYorkCity". Next thing is that replace method returns new string so your code will take no effect. It should be:
values[i] = values[i].replace(/\s+/g, '');

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