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
Related
I'm building a quote generator, and there is a product field where a user can select a product, select the quantity, then add another if they wish.
I'm using an each function to loop through all the products they add to sum the price.
For regular values, my JS is running great, but I want to add a second price (minimum price) that the product can be sold for. I've added the data as an attribute and i'm trying to use the same method to pull the price from the attribute, but it just keeps returning 'undefined'!!!!
HTML
<select class="form-control onChangePrice system1" name="SystemModel">
<option value="">Select...</option>
<option value="3300" data-min-price="3000">System 1</option>
<option value="4500" data-min-price="4000">System 2</option>
<option value="6000" data-min-price="5500">System 3</option>
<option value="6000" data-min-price="5500">System 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
<input class="form-control onChangePrice systemNumber" type="number" name="SystemModelAmount" value="1">
</div>
JS
var systemTotal = 0;
var systemMin = 0;
var i = 0;
$('.system1').each(function(){
if (this.value != "") {
systemEachMin = $(this).data("minPrice");
console.log(systemEachMin);
systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
systemTotal += parseFloat(systemEachTotal);
systemMin += parseFloat(systemEachMin);
};
i++;
});
The code works flawlessly for the regular value of the option, i just cant get it to repeat for the data attribute!
Thanks
You're doing a couple of things slightly wrong here:
$('.system1').each(function(){
should be:
$('.system1 option').each(function(){
and
systemEachMin = $(this).data("minPrice");
should be:
systemEachMin = $(this).data("min-price");
So in full:
var systemTotal = 0;
var systemMin = 0;
var i = 0;
$('.system1 option').each(function(){
if (this.value != "") {
systemEachMin = $(this).data("min-price");
console.log(systemEachMin);
systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
systemTotal += parseFloat(systemEachTotal);
systemMin += parseFloat(systemEachMin);
};
i++;
});
$(this).data("minPrice"); refers to the select tag and not the options tag, there is no data-min-price on the select tag.
this.options will return all the options in an array
or you could use the following for the selected options data attribute
$(this).find('option:selected').data("minPrice")
or
$("option:selected", this).data("minPrice")
I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};
I'm trying to change a value from a select tag using JavaScript. Let's say that I have this textbox, and if that textbox is null, no changes will be done and the value of the select tag options will be as is. But if that textbox is filled, then I have to assign a different value aside from the ones in the select tag options.
Here's what I'm trying to do:
HTML:
<input type="text" id="txtTest" />
<select name="rdoSelect" id="rdoSelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
JavaScript:
if (document.getElementById('txtTest').value===null)
{
document.getElementById('rdoSelect').value;
}
else
{
document.getElementById('rdoSelect').value = "option 3";
}
I can't make it work. I've tried pointing it to an element/variable rather than to a value and it still doesn't work:
var test = document.getElementById('rdoSelect');
test.value = "option 3";
I need help, please. Thanks!
Try using SelectIndex method. Please refer the below code.
I added OnChange event to input text to test this sample.
<html>
<head>
<script language="javascript">
function test()
{
if (document.getElementById('txtTest').value=='')
{
document.getElementById("rdoSelect").selectedIndex = 0;
}
else
{
document.getElementById("rdoSelect").selectedIndex = 1;
}
}
</script>
</head>
<body>
<input type="text" id="txtTest" onchange="test();" />
<select name="rdoSelect" id="rdoSelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
</body>
</html>
HTMLSelectElement doesn't let you set the value directly. It's possible to have many or zero <option>s with a particular value, so it's not a straightforward 1:1 mapping.
To select an option you can either set its selected property to true, or set the selectedIndex property of the select to the option number.
There is no option 3 in your select—are you trying to add a new option?
eg
function setOrCreateSelectValue(select, value) {
for (var i= select.options.length; i-->0;) {
if (select.options[i].value==value) {
select.selectedIndex= i;
return;
}
}
select.options[select.options.length]= new Option(value, value, true, true);
}
Is this happening on button click or onkeyup? Either way in the function you can add value to dropdownlist using this:
dropdownlist.append(
$("<option selected='selected'></option>").val(sValId).html(sVal)
);
Or you colud try this
var optn = document.createElement("OPTION");
optn.text = "--Select--";
optn.value = "0";
baseCurve.options.add(optn);`
if (document.getElementById('txtTest').value===null)
{
document.getElementById('rdoSelect').value;
}
else
{
var val = document.getElementById('txtTest').value
for(var i, j = 0; i = rdoSelect.options[j]; j++) {
if(i.value == val) {
rdoSelect.selectedIndex = j;
break;
}
}
}
Take a look at this jsfiddle, it's using jquery, which
is probably the most common solution. Hope it helps.
http://jsfiddle.net/GkLsZ/
$(function() {
$('#btnChange').on('click', function() {
var value = $.trim($('#txtTest').val());
if (!!value) {
$('#rdoSelect')
.append($("<option></option>")
.attr("value", value)
.attr("selected", "selected")
.text(value));
}
});
});
I have an HTML page in which I have 2 selects.
<select id="field" name="field" onchange="checkValidOption();">
<option />
<option value="Plugin ID">Plugin ID</option>
<option value="Name">Name</option>
</select>
<select id="operator" name="operator" onchange="checkValidOption();">
<option />
<option value="EQUALS">EQUALS</option>
<option value="CONTAINS">CONTAINS</option>
<option value="NOT CONTAINS">NOT CONTAINS</option>
<option value="REGEX">REGEX</option>
</select>
What I'd like to happen is that checkValidOption() could make it so that if "Plugin ID" is selected in field that the only option is EQUALS (and it's selected) and otherwise all the other options are available. Any idea on how to approach this?
I tried changing the innerHTML of the operator select in JS:
document.getElementById("operator").innerHTML =
"<option value='EQUALS'>EQUALS</option>";
However this results in an empty select (this would also include manually setting the many options for going back to having all the ones listed above).
I can't think of another solution, any help would be greatly appreciated.
Try this:
Demo here
var field = document.getElementById('field');
var operator = document.getElementById('operator');
field.onchange = function () { fieldcheck(); }
operator.onchange = function () { fieldcheck(); }
fieldcheck();
function fieldcheck() {
if (field.value == 'Plugin ID') {
for (i = 0; i < operator.options.length; ++i) {
if (operator.options[i].value != 'EQUALS') {
operator.options[i].disabled = true;
}
};
operator.value = 'EQUALS';
} else {
for (i = 0; i < operator.options.length; ++i) {
operator.options[i].disabled = false;
};
}
}
To manipulate options when Plugin ID was selected:
function checkValidOption(){
var x=document.getElementById("field");
var y=document.getElementById("operator");
if (x.options[1].selected === true){
document.getElementById("operator").options[1].selected = true;
for(var i=0; i<y.length; i++){
if (i !== 1){
//disabling the other options
document.getElementById("operator").options[i].disabled = true;
}
}
}
else{
for(var i=0; i<y.length; i++){
//enabling the other options
document.getElementById("operator").options[i].disabled = false;
}
}
}
Here's a link to fiddle
A select field doesn't use the innerHTML method, you need to use value.
document.getElementById("operator").value = "...";
heres a jquery solution.
every time the first select changes, it produces new options from an array for the 2nd select. issue here is i had to change the option values of the first select to 0 and 1 to select which value in the array, you can manipulate those later if you are storing this info somewhere
http://jsfiddle.net/2TZJh/
$(document).ready(function() {
$("#field").change(function() {
var val = $(this).val();
$("#operator").html(options[val]);
});
var options = [
'<option value="EQUALS">EQUALS</option>',
'<option></option><option value="EQUALS">EQUALS</option><option value="CONTAINS">CONTAINS</option> <option value="NOT CONTAINS">NOT CONTAINS</option> <option value="REGEX">REGEX</option>'
];
});
If I have select element with values which are different from their labels, how can I replace all of the labels with the corresponding values?
Secondly, how can I sort the list alphabetically with the values, all without using any frameworks?
Input:
<select name="options" >
<option value="apple">Fruit</option>
<option value="rye">Bread</option>
<option value="beer">Beverage</option>
</select>
Output:
<select name="options" >
<option value="apple">apple</option>
<option value="beer">beer</option>
<option value="rye">rye</option>
</select>
Sure, using getElementsByTagName() and innerHTML:
var allOptions = document.getElementsByTagName("option");
for (var i=0; i<allOptions.length; i++) {
allOptions[i].innerHTML = allOptions[i].value;
}
Here it is in action.
To sort the options alphabetically, see: Javascript to sort contents of select element
If you would like them to be identical, you can simply omit the value attribute - the string inside the option tag will then be sent to the server as the value. Take a look here: http://www.w3schools.com/tags/att_option_value.asp.
You can do this:
<select name="options" >
<option value="apple">Fruit</option>
<option value="rye">Bread</option>
<option value="beer">Beverage</option>
</select>
<script>
var options = document.getElementsByName("options")[0].querySelectorAll("option");
Array.prototype.slice.call(options).map(function (option) {
option.innerHTML = option.value;
});
</script>
You can encapsulate this in a function to order your select, and order when you remove or add any element to your select.
The function would be something like this:
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
And you should call it like :
sortSelect(document.getElementsByName("options"));