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
Javascript and I will never be best friends.
I try to set a checkbox to checked by changing the elements from a dropdownlist.
This is the snippet
<select name="change_status_to" id="sel">
<option>....</option>
<option>....</option>
</select>
<input type="checkbox" name="do_status_change" value="on">
How could I use Javascript with the onchange-event to set the checkbox to the state checked?
You can set its .checked property:
document.getElementById("do_status_change").checked = true;
document.getElementById("do_status_change").checked = false;
However, you need to set an id; the name attribute will not suffice.
> Example <
Here is an example of why you should be friends with javascript.
JSFiddle - http://jsfiddle.net/juc7Q/1/
HTML
You're feeling toward Javascript
<select name="friends" id="friends">
<option value="love">I love JS</option>
<option value="weird">JS is weird</option>
<option value="misunderstood">Are we speaking the same language?</option>
</select>
<button id="selectWeird">Keep JS Weird</button>
<div>
<input type="checkbox" id="we_friends"> - Friends?
</div>
JavaScript
//Select this using js
var list = document.getElementById('friends');
var cb = document.getElementById('we_friends');
//Add event when change happens
list.onchange = function () {
var value = list.value;
if(value == 'love') {
alert('I knew you would come around');
cb.setAttribute('checked', '');
} else if(value == 'weird') {
alert('And I like being weird :-)!!');
cb.removeAttribute('checked');
} else {
alert('And you think I understand you?');
cb.removeAttribute('checked');
}
}
//Change to 'Weird' when I click on it
var btn = document.getElementById('selectWeird');
btn.onclick = function () {
list.options.selectedIndex = 1;
}
I would like to add some functionality with the below code that only 5 times one can click the add button.
Also I would like to add a delete button with every replicated so when clicked, div is deleted and the counter of the 5 times is decreased.
HTML:
<button id="button" onlick="duplicate()">Add another plan</button>
<div id="duplicater">
<p>Choose Your Mobile Plan</p>
<select>
<option value="1">Package 1</option>
<option value="2">Package 2</option>
<option value="3">Package 3</option>
<option value="4">Package 4</option>
<option value="5">Package 5</option>
<option value="6">Package 6</option>
</select>
</div>
JS:
document.getElementById('button').onclick = duplicate;
var i = 0; var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone); }
A JSFiddle can be found here: http://jsfiddle.net/7x4re/
You just have to add an if before your duplicate code:
document.getElementById('button').onclick = duplicate;
var original = document.getElementById('duplicater');
var i = 1;
function duplicate() {
if (i < 6) {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + i++; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
}
1. Example on JSFiddle.
If you want to disable the button when 5 times clicked, below is the code:
document.getElementById('button').onclick = duplicate;
var original = document.getElementById('duplicater');
var i = 1;
var max = 5;
function duplicate() {
if (i < max + 1) {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + i++; // there can only be one element with an ID
original.parentNode.appendChild(clone);
if (i > max) document.getElementById('button').disabled = true;
}
}
2. And an example on JSFiddle.
3. Finally the master solution with add and remove button. But just in a JSFiddle because the code is large...
4. I know it's already a lot but I improved all this, here is the JSFiddle with add and remove button, disable enable function, min max variable and without any i or count varaible, so it's the ultimate master solution ;)
You can add a button to delete the element like this:
<button id="button">Add another plan</button>
<div id="duplicater">
<p>Choose Your Mobile Plan</p>
<select>
<option value="1">Package 1</option>
<option value="2">Package 2</option>
<option value="3">Package 3</option>
<option value="4">Package 4</option>
<option value="5">Package 5</option>
<option value="6">Package 6</option>
</select>
<button class='removebutton'>Delete</button>
</div>
You can enable a function to fire when it's clicked using jquery:
$('body').on('click', ".removebutton", remove);
Finally, the remove handler can remove the clicked element:
function remove() {
if (count > 1) {
if ($(this).parent().attr('id') != 'duplicater') {
$(this).parent().remove();
count--;
} else {
alert("You can't delete the first plan");
}
} else {
alert("You can't delete the first plan");
}
}
http://jsfiddle.net/JVzCt/
I've used a similar approach to the counter as used by ReeCube.
As this uses jquery, you need to include it, either from your local machine or from somewhere else e.g.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
All the js code should be wrapped in the standard jquery ready function:
$(function(){
// Put your js code here.
});
I have 2 drop down menus which both have 'name'=list1. I also have 2 radio buttons 'yes' or 'no'. When select no all dropdown menus should be hidden, when selected 'yes' all drop down menus should show however at the minute only one is showing when clicked yes none showing when clicked no.
JavaScript code to hide:
<script type="text/javascript">
function showDiv(targetElement,toggleElementClass){
var els,
i;
if (targetElement.checked) {
els = document.getElementsByClassName(toggleElementClass);
for (i=0; i < els.length; i++) {
els[i].style.visibility = "visible";
els[i].style.display = "block";
}
}
}
function HideDiv(targetElement,toggleElementClass){
var els,
i;
if (targetElement.checked) {
els = document.getElementsByClassName(toggleElementClass);
for (i=0; i < els.length; i++) {
els[i].style.visibility = "visible";
els[i].style.display = "block";
}
// and similar for hideDiv()
</script>
code for 1st dropdwon:
<div style="display: none;" class="list1" >
<select name="colour">
<option>Please Select</option>
<option>red</option>
<option>orange</option>
<option>blue</option>
</select>
code for 2nd drop down:
<div id="list2" style="display: none;" class="list2" >
<select name="shade">
<option>Please Select</option>
<option>dark</option>
<option>light</option>
</select>
</div>
only the 1st is displaying on webpage. does anyone know why?
The id attribute is supposed to be unique, i.e., no two elements should have the same id. If you have two (or more) elements with the same id the document.getElementById() method will likely return the first - behaviour may vary from browser to browser but in any case it will definitely only return either one element or null.
If you want to apply the same change to multiple similar elements you could try giving those elements the same class and select them with the .getElementsByClassName() method:
<div class="list1"></div>
<div class="list1"></div>
<script>
function showDiv(targetElement,toggleElementClass){
var els,
i;
if (targetElement.checked) {
els = document.getElementsByClassName(toggleElementClass);
for (i=0; i < els.length; i++) {
els[i].style.visibility = "visible";
els[i].style.display = "block";
}
}
}
// and similar for hideDiv()
</script>
Another method you might like to look into is .getElementsByTagName().
Notice that .getElementById() is "element", singular, while the other two methods I mentioned get "elements", plural...
EDIT: My apologies, I don't think IE supported .getElementsByClassName() until version 9. If you are using IE8 you can substitute the following line in the above function:
els = document.querySelectorAll("div." + toggleElementClass);
and the rest should work as is. Here is a demo that I've tested as working in IE8: http://jsfiddle.net/CVS2F/1/
Alternatively for even older IE version support where you can't use .querySelectorAll() you could just use .getElementsByTagName("div") and then within the loop test each returned element to see if it has the class you care about. Here's an updated demo that works that way: http://jsfiddle.net/CVS2F/2/
To clear all your confusion, I came up with working test HTML below. Save the code as HTML and test if is it give what you wanted?
What you need to do is change 'id' to 'class', so you can select multiple elements into an array. Iterate that array and apply the style.
<html>
<head>
<script>
window.onload=registerEventHandlers;
document.getElementsByClassName = function (cn) {
var rx = new RegExp("(?:^|\\s)" + cn+ "(?:$|\\s)");
var allT = document.getElementsByTagName("*"), allCN = [], ac="", i = 0, a;
while (a = allT[i=i+1]) {
ac=a.className;
if ( ac && ac.indexOf(cn) !==-1) {
if(ac===cn){ allCN[allCN.length] = a; continue; }
rx.test(ac) ? (allCN[allCN.length] = a) : 0;
}
}
return allCN;
}
function registerEventHandlers()
{
document.getElementById("radio1").onclick = function(){
hideDiv(this,"list1")
};
document.getElementById("radio2").onclick = function(){
showDiv(this,"list1")
};
}
function showDiv(targetElement,toggleElementId){
var showAll=document.getElementsByClassName(toggleElementId);
for(i in showAll){
showAll[i].style.visibility="visible";
showAll[i].style.display="block";
}
}
function hideDiv(targetElement,toggleElementId){
var hideAll=document.getElementsByClassName(toggleElementId);
for(i in hideAll){
hideAll[i].style.visibility="hidden";
hideAll[i].style.display="none";
}
}
</script>
</head>
<body>
Yes:<input type="radio" id="radio2" name="yesNo" value="yes" />
No:<input type="radio" id="radio1" name="yesNo" value="no"/>
<div class="list1" style="display: none;" >
<select name="colour">
<option>Please Select</option>
<option>red</option>
<option>orange</option>
<option>blue</option>
</select>
</div>
<div class="list1" style="display: none;" >
<select name="shade">
<option>Please Select</option>
<option>dark</option>
<option>light</option>
</select>
</div>
</body>
</html>
Let's say that I have select list with 3 options inside:
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Now, I want to update one of these options, so i create textfield & button.
The option appear inside the textfield everytime i press on one of the options at the select list.
Can someone direct me what do i need to do?
thanks
Adding up to the first example that we had this morning jsfiddle
HTML:
<select id='myselect'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
<input type='text' value='1' name='mytext' id='mytext' />
<button value='add' id='addbtn' name='addbtn'>add</button>
<button value='edit' id='editbtn' name='editbtn'>edit</button>
<button value='delete' id='deletebtn' name='deletebtn'>delete</button>
JavaScript:
var myselect = document.getElementById('myselect');
function createOption() {
var currentText = document.getElementById('mytext').value;
var objOption = document.createElement("option");
objOption.text = currentText;
objOption.value = currentText;
//myselect.add(objOption);
myselect.options.add(objOption);
}
function editOption() {
myselect.options[myselect.selectedIndex].text = document.getElementById('mytext').value;
myselect.options[myselect.selectedIndex].value = document.getElementById('mytext').value;
}
function deleteOption() {
myselect.options[myselect.selectedIndex] = null;
if (myselect.options.length == 0) document.getElementById('mytext').value = '';
else document.getElementById('mytext').value = myselect.options[myselect.selectedIndex].text;
}
document.getElementById('addbtn').onclick = createOption;
document.getElementById('editbtn').onclick = editOption;
document.getElementById('deletebtn').onclick = deleteOption;
myselect.onchange = function() {
document.getElementById('mytext').value = myselect.value;
}
Basically i added an edit field that when clicked it'll edit the value and text of the currently selected option, and when you select a new option it'll propogate the textfield with the currently selected option so you can edit it. Additionally, i also added a delete function since i figure you might need it in the future.
Use jquery :selected selector and val() method.
$('select:selected').val($('input_textbox').val());
First of all always give an ID to your input tags. For eg in this case you can do something like: <select id='myDropDown'>
Once you have the ID's in place its simple matter of picking up the new value from textbox and inserting it into the dropdown:
Eg:
// Lets assume the textbox is called 'myTextBox'
// grab the value in the textbox
var textboxValue = document.getElementById('myTextBox').value;
// Create a new DOM element to be inserted into Select tag
var newOption = document.createElement('option');
newOption.text = textboxValue;
newOption.value = textboxValue;
// get handle to the dropdown
var dropDown = document.getElementById('myDropDown');
// insert the new option tag into the dropdown.
try {
dropDown.add(newOption, null); // standards compliant; doesn't work in some versions of IE
}
catch(ex) {
dropDown.add(newOption); // IE only
}
Below is a pure js example using your markup.
EDIT
After rereading your question Im not sure if you wanted the option to update when a user clicked the button or not.. To just put the option into an input you can do this.
var select = document.getElementsByTagName("select")[0],
input = document.getElementById("inputEl");
select.onchange = function(){
input.value = this[this.selectedIndex].text;
}
To update the option to what the user typed in is below.
http://jsfiddle.net/loktar/24cHN/6/
Markup
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<br/>
<input type="text" id="inputEl"/>
<button id="button">Update</button>
Javascript
var select = document.getElementsByTagName("select")[0],
input = document.getElementById("inputEl"),
button = document.getElementById("button");
select.onchange = function(){
input.value = this[this.selectedIndex].text;
var selected = this,
selectedIndex = this.selectedIndex;
button.onclick = function(){
selected[selectedIndex].text = input.value;
}
}