I have a dropdown list which looks like this:
<select id="cityID">
<option value="mission">Mission</option>
<option value="bakersfield">Bakersfield</option>
<option value="knoxville">Knoxville</option>
</select>
And my code to get the value is:
var select = document.getElementById('cityID');
var text = select.options[select.selectedIndex].text;
text.innerHTML = cityID.value;
text.onchange = function(e) {
text.innerHTML = e.target.value;
}
The value always chooses the first item. How can I get it to accept the cityID and change the page,
I'm sure its a formatting or typo or wrong value ?
onchange event is trigger from the select element
your text variable seems to be an HTML element because you set its innerHTML property
a select element has a "value" property so you don't need to get it from the selectedIndex of the options.
var select = document.getElementById('cityID');
var textEl = document.getElementById("text")
text.innerHTML = select.value;
select.onchange = function(e) {
textEl.innerHTML = e.target.value;
}
<select id="cityID">
<option value="mission">Mission</option>
<option value="bakersfield">Bakersfield</option>
<option value="knoxville">Knoxville</option>
</select>
<p id="text"></p>
You could achieve this using addEventListener also.
var select = document.getElementById('cityID');
var textEl = document.getElementById("text")
select.addEventListener("change", (e) => {
textEl.innerText = e.target.value;
})
How can I re-order the comma delimited value of a select multiple element based on the order in which the options were selected by the user instead of the order of the options in the html?
For example:
<select multiple>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
... If the user selects "3", then "1", then "2", the returned value of the select will be "1,2,3". How can I make it return "3,1,2"?
Note, I am using jQuery and HTML5, so I can use those tools if needed.
Thanks!
This records the click of each elements add saves it to an array. When an item is deselected it is removed from the array.
var vals = [];
$(document).ready(function(e) {
$('#selector').change(function(e) {
for(var i=0; i <$('#selector option').length; i++) {
if ($($('#selector option')[i]).prop('selected') ) {
if (!vals.includes(i)) {
vals.push(i);
}
} else {
if (vals.includes(i)) {
vals.splice(vals.indexOf(i), 1);
}
}
}
})
$("#final").click(function(e) {
var order = '';
vals.forEach(function(ele) {
order += $($('#selector option')[ele]).val() + ',';
})
console.log(order);
})
})
Codepen: http://codepen.io/nobrien/pen/pydQjZ
None of the proposed solutions floated my boat, so I came up with this:
My solution is to add an html5 attribute to the multiselect element, data-sorted-values, to which I append new values, and remove un-selected values, based on the latest change.
The effect in the end is that data-sorted-values can be queried at anytime to get the current list of user-ordered values. Also, all selected options hold an attribute of "selected".
I hope this can help someone else out there...
https://jsfiddle.net/p1xelarchitect/3c5qt4a1/
HTML:
<select onChange="update(this)" data-sorted-values="" multiple>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Javasript:
function update(menu) {
// nothing selected
if ($(menu).val() == null)
{
$.each($(menu).find('option'), function(i)
{
$(this).removeAttr('selected');
$(menu).attr('data-sorted-values', '');
});
}
// at least 1 item selected
else
{
$.each($(menu).find('option'), function(i)
{
var vals = $(menu).val().join(' ');
var opt = $(this).text();
if (vals.indexOf(opt) > -1)
{
// most recent selection
if ($(this).attr('selected') != 'selected')
{
$(menu).attr('data-sorted-values', $(menu).attr('data-sorted-values') + $(this).text() + ' ');
$(this).attr('selected', 'selected');
}
}
else
{
// most recent deletion
if ($(this).attr('selected') == 'selected')
{
var string = $(menu).attr('data-sorted-values').replace(new RegExp(opt, 'g'), '');
$(menu).attr('data-sorted-values', string);
$(this).removeAttr('selected');
}
}
});
}
}
try this https://jsfiddle.net/ksojitra00023/76Luf1zs/
<select multiple>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<div id="output"></div>
$('select').click(function(){
$("#output").append($(this).val());
});
var data = '3,1,2';
var dataarray=data.split(",");
var length =dataarray.length;
for(i=0;i<length;i++){
// Set the value
$('#select').multiSelect('select',dataarray[i]);
}
I have a function that based on a checkbox id determines a price value. This works fine except I need to change the checkbox to a select. I tried to change the line:
if(peo14.checked==true)
To this:
if(peo14.select==Yes)
This did not work...how do I alter this to a Yes/No select?
function peoPrice()
{
var peoPrice=0;
//Get a reference to the form id="quicksheet"
var theForm = document.forms["quicksheet"];
//Get a reference to the checkbox id
var peo14 = theForm.elements["peo14"];
//If they checked the box set peoPrice to value
if(peo14.checked==true)
{
peoPrice=199;
}
//finally we return the peoPrice
return peoPrice;
}
You have to use the .options property and choose the selected index, then get the value of that index.
if (peo14.options[ peo14.selectedIndex ].value === 'Yes') {
peoPrice = 199;
}
Select Box
<select id="peo14" name='peo14' >
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
function peoPrice()
{
var peoPrice=0;
var e = document.getElementById("peo14");
var peo14val = e.options[e.selectedIndex].value;
if(peo14val=="Yes")
{
peoPrice=199;
}
//finally we return the peoPrice
return peoPrice;
}
I'm integrating Postcode anywhere with my web project. I'm using a drop drop for the county/state field. Postcode anywhere returns the name of the County. Can I change the Selected Index when I only have the name? (I'm using a number for the value field which relates to a database field).
I tried the following:
var f = document.getElementById("state_dropdown");
f.options.[f.selectedIndex].text = response[0].County;
I've tried to include the drop down code html here but I can't get it to work properly for some reason.
But of course this just changes the text field for the item in the drop down that is already selected.
I can query the database and find out what ID I have assigned the county but I'd rather not if there is another way.
Loop over the options until you have a match:
for (var i = 0; i < f.options.length; i++) {
if (f.options[i].text == response[0].Country) {
f.options.selectedIndex = i;
break;
}
}
Demo.
I would make a function and loop over the labels:
See: http://jsfiddle.net/Y3kYH/
<select id="country" name="countryselect" size="1">
<option value="1230">A</option>
<option value="1010">B</option>
<option value="1213">C</option>
<option value="1013">D</option>
</select>
JavaScript
function selectElementByName(id, name) {
f = document.getElementById(id);
for(i=0;i<f.options.length;i++){
if(f.options[i].label == name){
f.options.selectedIndex = i;
break;
}
}
}
selectElementByName("country","B");
Just a variation on other answers:
<script type="text/javascript">
function setValue(el, value) {
var sel = el.form.sel0;
var i = sel.options.length;
while (i--) {
sel.options[i].selected = sel.options[i].text == value;
}
}
</script>
<form>
<select name="sel0">
<option value="0" selected>China
<option value="1">Russia
</select>
<button type="button" onclick="setValue(this, 'Russia');">Set to Russia</button>
<input type="reset">
</form>
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