I would like to iterate through the selected values from a multiple select box and check them against a string, returning false as soon as a match is not found. First I tried:
var exampleString = "example";
var mySelections = $("#mySelect option:selected");
for (selection in mySelections) {
if (exampleString.indexOf(mySelections[selection].text()) === -1) {
return false;
};
};
This code gives me an error, however: "text is not a function". I am given to understand that this is because using the index gets the option object itself, not wrapped in jQuery, and it is jQuery that provides the text() method.
I tried an alternative version using the each function:
var result = $("#mySelect option:selected").each(function () {
if (exampleString.indexOf($( this ).text()) === -1) {
return false;
}
});
However, I do not understand the result I'm getting. I naively assumed that my variable result would be set to false or true, but it seems to just return the objects being iterated over. Is there any way to access the results of those string comparisons short of creating a global variable that gets set to true or false inside the function?
Edited to add: upon request, here's the relevant html:
<select multiple="" class="filterSelect" id="mySelect" style="display: none;">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
This is what I would do (I'm not a jQuery user any more):
let testStr = "dd";
document.getElementById('sel').addEventListener('change', (e) => {
const values = []
for (let i=0; i<e.target.selectedOptions.length; i++) {
values.push(e.target.selectedOptions[i].value);
}
console.log(!values.includes(testStr));
return !values.includes(testStr);
})
<select id="sel" multiple>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
<option value="ee">ee</option>
</select>
I simply wish to capture the options value at the time of change.
My code works when ran in console as individual lines however even after the function is called the variable listObj and eventValue remain null.
window.onload = function() {
document.getElementById("listSelector").addEventListener("change",
findCarFunc);
alert("Loaded");
}
function findCarFunc() {
alert("you changed");
var listObj = document.getElementById("listSelector");
var eventValue = listObj.value;
}
<select id="listSelector">
<option value="defaultManufactuer" selected = "selected">Manufacturer</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
Now the function returns a string however, I wanted to add quotation marks to string as I am going to use it to identify the relevant element IDs.
Can I actually do what I am attempting to below? I feel I may have confused myself,
window.onload = function () {
document.getElementById("listSelector").addEventListener("change", populateContainer);
alert("Loaded");
}
function findCarFunc() {
alert("you changed");
var listObj = document.getElementById("listSelector").value;
console.log(listObj);
}
function populateContainer() {
alert("Container Event Loaded")
//Div to append child on once the function has returned the
//element string.
var target = document.getElementById("target");
//This is where I attempt to capture and manipulate the string by
//concatinating the quote marks onto the .
var str = "'"+findCarFunc()+"'";
console.log(str);
}
You can get the value of the selected option using
var eventValue = listObj.options[listObj.selectedIndex].value;
Edit. I have updated my answer to fit your needs mentioned in comments.
The problem with your code is that your are not returning anything in your findCarFunc(), meaning this function will return undefined by default.
window.onload = function () {
document.getElementById("listSelector").addEventListener("change", populateContainer);
alert("Loaded");
}
function findCarFunc() {
alert("you changed");
var listObj = document.getElementById("listSelector").value;
return listObj;
}
function populateContainer() {
alert("Container Event Loaded")
//Div to append child on once the function has returned the
//element string.
var target = document.getElementById("target");
//This is where I attempt to capture and manipulate the string by
//concatinating the quote marks onto the .
var str = "'"+findCarFunc()+"'";
console.log(str);
}
<select id = "listSelector">
<option value="defaultManufactuer" selected = "selected">Manufacturer</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
window.onload = function () {
document.getElementById("listSelector").addEventListener("change", findCarFunc);
alert("Loaded");
}
function findCarFunc() {
alert("you changed");
var listObj = document.getElementById("listSelector").value;
console.log(listObj);
}
<select id = "listSelector">
<option value="defaultManufactuer" selected = "selected">Manufacturer</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
I have a SELECT element and also a INPUT element on a form and I need to get always the concatenated value (the result of SELECT + INPUT) when any of those two elements are updated this include:
SELECT change the selected value
User start typing in INPUT element
But I don't know how to achieve this. See this example below:
<select id="rif" name="rif" class="form-control">
<option value="J">J</option>
<option value="G">G</option>
<option value="V">V</option>
<option value="E">E</option>
</select>
<input type="text" required="required" value="" name="_username" class="form-control numeric" id="username">
Input values could be:
select#rif = "J"
input#username ="string"
output = "Jstring"
select#rif = "V"
input#username ="str"
output = "Vstr"
But then I leave input#username without changes but change select#rif as follow:
select#rif = "J"
input#username ="str"
output = "Jstr"
select#rif = "V"
input#username ="str"
output = "Vstr"
In other words the concatenation needs to be in both direction and output value should change all the time when select change their selected value or input change the text inside it by keyup or any other event. Can any give me some help?
This should work:
$(function(){
function result(){
var s = $('#rif').find(":selected").val(), i = $('#username').val();
return s + i;
}
$('#rif').on('change', result);
$('#username').on('keyup', result);
});
First declare a function that reads the values of the dropdown and the input fields and return the concatenation of those. Finally use the change event for the select menu and the keyup for the input to catch their editing and return the result of them as a callback.
Please refer the fiddle.
HTML:
<select id="select">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<input type="text" id="text">
The result is <span id="result"></span>
JavaScript:
var selectNode = document.querySelector('#select');
var textNode = document.querySelector('#text');
var resultNode = document.querySelector('#result');
var updateResult = function(e) {
var result = selectNode.value + textNode.value;
resultNode.innerHTML = result;
}
selectNode.addEventListener('change', updateResult);
textNode.addEventListener('input', updateResult);
Javascript to listen to both elements changeing and then giving you the concatenated string
$('#rif, #username').on('change', function () {
var str = $('#rif').val() + $('#username').val();
alert(str);
});
Demo:http://jsfiddle.net/robschmuecker/rGu4k/
I have a form in html that contains a drop down menu like so
<form name= "gadget_selector">
<select name= "gadget">
<option value = 0> Something </option>
<option value = 1> Something else </option>
//etc..
</select>
</form>
And I want to access the value of the selected option in a javascript function like so
function someFunction(){
//var option = value of selected menu option
}
How would I do this?
var option = document.getElementById('gadget').value;
Set gadget as the id for the select as well, like this:
<select id="gadget" name="gadget">
<option value = 0> Something </option>
<option value = 1> Something else </option>
//etc..
</select>
assign id to select box "gadget":
<select name= "gadget" id="gadget">
<option value = 0> Something </option>
<option value = 1> Something else </option>
//etc..
</select>
Now get selected value in javascript like below :
function GetSelectedItem() {
var option = document.getElementById('gadget').value;
}
Include an id attribute to select element and do as below, i am sure i will work,
var obj = document.getElementById("gadget");
alert(obj.value); // returns selected option value (1st method)
var selectedOption = obj.options[obj.selectedIndex]; // returns selected option element
alert(selectedOption.value); // return selected option value (2nd method)
example : http://jsfiddle.net/zUBpz/
First, assign an id to your <select> tag.
<select id='gadget' name= "gadget">
Then, get its value
if (document.getElementById('gadget')) {
var val = document.getElementById('gadget').value;
alert(val);
}
You can access by id, like this:=
<form name= "gadget_selector" >
<select name= "gadget" id='sel'>
<option value = 0> Something </option>
<option value = 1> Something else </option>
//etc..
</select>
</form>
function getvalue(){
if(document.getElementById('sel'))
{
alert(document.getElementById('sel').value);
var option = document.getElementById('sel').value;
}
}
here forms[0] is the form number starting from 0 from top to bottom of page
function someFunction(){
var option = window.document.forms[0].gadget.value;
}
Old question, but maybe other people get here like me so I'll add my solution:
The cleanest approach would be to have a reference to the select field, have the select backed by a model and add a watcher like this:
<script>
export default {
name: 'MyComponent',
data() {
return {
myValueName: 123
};
},
watch: {
myValueName() {
//
// Will log "Value: 123" and "Value: 456" instead of
// "123" and "456".
//
console.log(this.$refs['mySelectRef'].selectedOptions[0].text);
}
}
}
</script>
<template>
<select ref="mySelectRef" v-model="myValueName">
<option :value="123">Value: 123</option>
<option :value="456">Value: 456</option>
</select>
</template>
<style>
</style>
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