I am trying to get (or show) values from Multiple Select using only Javascritpt. Let's say, the user can select multiple options from here, and when they click the 'Show Select' button they can see what are the values of these options.
I took the idea about 'selected' attribute from here
But, the code didn't work. Any help?
<select id ="selectOptions" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<button onclick="myFunction()">Show Selects</button>
<script>
function myFunction()
{
var numOfOptions = document.getElementById("slectOptions").options.length;
var n=0;
for (n=0; n<numOfOptions; n++)
{
// I tried to use a for loop that will go around from option 0 to 3,
//and through 'selected' attribute wanted to check the condition if the option is selected then only show the values
// I still couldn't figure out if the loop is working at all
if (document.getElementById("slectOptions")[n].selected)
{
var x = document.getElementById("slectOptions").value;
window.alert(x);}
}
}
Just use
var select = document.getElementById("selectOptions");
console.log(select.selectedOptions);
Iterate over the options and check checked property. Although there is a simple type in your selector where missing e in the string.
function myFunction() {
var options = document.getElementById("selectOptions").options;
for (var n = 0; n < options.length; n++) {
if (options[n].selected) {
console.log(options[n].value);
}
}
}
<select id="selectOptions" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<button onclick="myFunction()">Show Selects</button>
Or use readonly selectedOptions property to get the collection of selected options.
function myFunction() {
var options = document.getElementById("selectOptions").selectedOptions;
for (var n = 0; n < options.length; n++) {
console.log(options[n].value);
}
}
<select id="selectOptions" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<button onclick="myFunction()">Show Selects</button>
<!DOCTYPE html>
<html>
<script>
function eraseText() {document.getElementById("txtChoices").value = "";
}
function SetMulti() {var txtChoices = document.getElementById("txtChoices"); txtChoices.value += document.getElementById("choiceNames").value;
}
</script>
</head>
<body>
<input type="text" id="txtChoices" readonly="readonly" placeholder="Multiple choice"/></br>
"Variable" Choice dropdown:
</br>
<select multiple="" name="choiceNames" id="choiceNames">
<option value="Long, ">Long, </option>
<option value="Short, ">Short, </option>
<option value="Red, ">Red, </option>
<option value="Curly, ">Curly, </option>
<option value="Straight, ">Straight, </option>
</select>
<button onclick="SetMulti()">Add</button>
<button onclick="eraseText()">Reset</button>
</body>
</html>
Related
I have a multiselect dropdown where I want to get the value of latest selected value. In my example, I've just used an alert to display the selected option. When I select 'volvo' it alerts volvo and now if I press ctrl and multiselect 'opel', I still get alerted 'volvo'. But I want it to alert 'opel'. I tried using an array to store the values but I'm not able to use the second option in the dropdown.
My actual code is about inserting these values dynamically to a new row in a table. But 'volvo' gets added evrytime instead of other selected options
Here's the code:
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
<select name="cars" onchange="myFucntion(this.value)" multiple>
<option value="volvo">Volvo</option>
<option value="bmw">Bmw</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
<script type="text/javascript">
function myFucntion(val) {
alert(val);
}
</script>
</body>
</html>
EDIT: There seems to be a problem with only selectpicker multiselect dropdown. It works fine when I remove selectpicker class. Is there anyway to solve it when using selectpicker?
You need to put a click handler on the options. Then just test whether the option is selected or not (so you don't alert when you're de-selecting the option).
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
<select name="cars" multiple>
<option value="volvo" onclick="myFunction(this)">Volvo</option>
<option value="bmw" onclick="myFunction(this)">Bmw</option>
<option value="opel" onclick="myFunction(this)">Opel</option>
<option value="audi" onclick="myFunction(this)">Audi</option>
</select>
<input type="submit">
</form>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
<script type="text/javascript">
function myFunction(option) {
if (option.selected) {
alert(option.text);
}
}
</script>
</body>
</html>
This gets the last selected item in your option list.
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
<select name="cars" onchange="myFucntion(this.value)" multiple>
<option value="volvo">Volvo</option>
<option value="bmw">Bmw</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
<script type="text/javascript">
var lastSelected = null;
function myFucntion(val) {
alert(lastSelected === null ? 'There was no last selected item' : lastSelected);
lastSelected = val;
}
</script>
</body>
</html>
I suspect this is not what you want. You would likely want all the selected items in the list:
//Function courtesy of https://stackoverflow.com/a/27781069/4875631
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;
}
function myFunction(select) {
var values = getSelectValues(select);
console.log(values);
}
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
<select name="cars" onchange="myFunction(this)" multiple>
<option value="volvo">Volvo</option>
<option value="bmw">Bmw</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
</body>
</html>
Changing the event to click and using the target.value should do the trick.
const elem = document.getElementById('elem');
elem.addEventListener('click', (e) => console.log(e.target.value));
<form action="/action_page.php">
<select name="cars" id='elem' multiple>
<option value="volvo">Volvo</option>
<option value="bmw">Bmw</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
I think we have to keep proper track of recent selection of the select values. Let's say user selects
A -> B-> C-> D
Then recent selection is D so we print D. Now what if user deselect option D. AT this case the proper recent tracking would work if you are able to print C, as C is recently selected before D. And so on when C is deselect. All of the answers above do not consider this. So i have my version of answer and logic here.
$(document).ready(function(){
var selectedValues = [];
$('#carsDdl').on('click',function(event){
var recentSelection = event.target.value;
var index = selectedValues.indexOf(recentSelection);
if(index === -1){
selectedValues.push(recentSelection);
}else{
selectedValues.splice(index,1);
}
if(selectedValues.length !== 0){
var recentSelection = selectedValues[selectedValues.length-1];
console.log('All selected cars: '+ selectedValues);
console.log('Recently selected car: '+ recentSelection);
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/action_page.php">
<select id = 'carsDdl' name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="bmw">Bmw</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
I added ability to find out appending and removing item from multiselect
var old_selected = [];
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;
}
function myFucntion(el){
new_selected = getSelectValues(el);
//find added elemnts
added = new_selected.filter(function(item){
return old_selected.indexOf(item)==-1
});
if(added.length>0)
alert(added+' added')
//find removed
removed = old_selected.filter(function(item){
return new_selected.indexOf(item)==-1
});
if(removed.length>0)
alert(removed+' removed')
old_selected = new_selected;
}
<form action="/action_page.php">
<select name="cars" onchange="myFucntion(this)" multiple>
<option value="volvo">Volvo</option>
<option value="bmw">Bmw</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
I want when someone selects a country out of my list the province in that country show up in the second select bar is this possible within html? And if not how do I do it with javascript.
<!DOCTYPE html>
<html>
<head>
<title>Gegevens</title>
</head>
<body>
<center>
<h1>Gegevens</h1>
</center>
Land:
<select id="countries">
<option value="Holland">Holland</option>
<option value="Denmark">Denmark</option>
<option value="England">England</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
</select><br>
Provincie:
<select> OPTIONS FOR HOLLAND
<option value="Gelderland">Gelderland</option>
<option value="Utrecht">Utrecht</option>
</select>
<select> OPTIONS FOR ENGLAND ETC...
<option value="Schotland">Schotland</option>
<option value="Wales">Wales</option>
</select>
<footer>Ga terug</footer>
</body>
</html>
You'll probably have to do this using JavaScript. I've edited your HTML a bit to make the selection process easier. There might be a way with HTML form elements, but try this:
var countrySelect = document.getElementById('countries'); //the main select
var countryClass = document.getElementsByClassName('country'); //the other selects
countrySelect.onchange = function(){
var selected = this.children[this.selectedIndex].value; //this is the value of the country select;
for(var i = 0; i < countryClass.length; i++)
countryClass[i].style.display = countryClass[i].id === selected ? 'block' : 'none';
}
<body>
<center>
<h1>Gegevens</h1>
</center>
Land:
<select id="countries">
<option disabled selected>Select Country</option>
<option value="Holland">Holland</option>
<option value="Denmark">Denmark</option>
<option value="England">England</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
</select><br>
Provincie:
<select class="country" id="Holland" style="display:none;">
<option disabled selected>Select Location</option>
<option value="Gelderland">Gelderland</option>
<option value="Utrecht">Utrecht</option>
</select>
<select class="country" id="England" style="display:none;">
<option disabled selected>Select Location</option>
<option value="Schotland">Schotland</option>
<option value="Wales">Wales</option>
</select>
</body>
I am not sure about the html way but the jquery way is pretty easy.
Handle option selected of countries. Based on the country selected hide/show provinces:
$(document).ready(function(){
$('#countries').on('change',function(){
var selectedCountry = $(this).find('option:selected').text();
switch (selectedCountry){
case 'Holland':
// hide show provice
break;
//etc
}
});
});
You need to use JS and play with elements display property.
After user selects a country hide province select (code snippet below hides all selects sharing toggle class), then identify which country was selected and show the province select for that country. Voilà!
<!DOCTYPE html>
<html>
<head>
<title>Gegevens</title>
</head>
<body>
<center>
<h1>Gegevens</h1>
</center>
Land:
<select id="countrySelect" onchange="toggleCountry()">
<option value="Holland">Holland</option>
<option value="England">England</option>
</select><br>
Provincie:
<select id="provinceHolland" class="toggle">
<option value="Gelderland">Gelderland</option>
<option value="Utrecht">Utrecht</option>
</select>
<select id="provinceEngland" class="toggle" style="display:none">
<option value="Schotland">Schotland</option>
<option value="Wales">Wales</option>
</select>
<footer>Ga terug</footer>
<script>
function toggleCountry() {
var list = document.getElementsByClassName("toggle");
for (var i = 0; i < list.length; i++) {
list[i].style.display = "none";
}
var sub = "province" + document.getElementById("countrySelect").value;
document.getElementById(sub).style.display = "inline";
}
</script>
</body>
I need your help,
Using javascript, how could I add some sort of data form validation that would be two-fold:
1st Event, [OnKeyUp] attached to all of the input boxes
2nd Event, [OnChange] attached to all of the select boxes
Typical User Scenarios
If there is any data present in any of the input boxes and no selected option values then { enable the search button } else { keep the search button disabled }
If there are any selected option values who’s option value is not null and no data present in all of then { enable the search button } else { keep the search button disabled }
<!DOCTYPE html>
<html>
<head></head>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
</html>
var car=$('#car'); var fruits=$('#fruits');
var veggie=$('#veggie'); var number = $('#number');
$('select').change(function(){
validate();
});
$('input').keyup(function(){
validate();
});
function validate(){
if(($(veggie).val()!='' || $(number).val()!='') &&
$(car).val()=='' && $(fruits).val()==''){
$('#search').prop('disabled',false);
}else if($(veggie).val()=='' && $(number).val()=='' &&
($(car).val()!='' || $(fruits).val()!='')){
$('#search').prop('disabled',false);
}else{
$('#search').prop('disabled',true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
I'm not 100% sure, but it looks like you want to enable the button if only one of the select elements has a value or one of the input elements has a value, but not if both (or neither) do.
If that's the case then this should work, and it allows you you add as many elements to it as you need by adding IDs to the arrays at the top.
https://jsfiddle.net/j7by6bsz/
var selectInputIds = ['fruits', 'car'];
var textInputIds = ['veggie', 'number'];
function setButtonState() {
var hasVal = function(arr) {
for(var i = 0; i < arr.length; i++) {
if(document.getElementById(arr[i]).value) {
return true;
}
}
return false;
};
var hasSelectValue = function () {
return hasVal(selectInputIds);
}
var hasTextValue = function () {
return hasVal(textInputIds);
}
var theButton = document.getElementById('search');
var s = hasSelectValue();
var t = hasTextValue();
theButton.disabled = ((s && t) || (!t && !s)); // you can do this bit smarter, but this is explicit
}
(function attachStuff (arr, evt) {
function listenIn(arr, evt) {
for(var i = 0; i < arr.length; i++) {
document.getElementById(arr[i]).addEventListener(evt, setButtonState);
}
}
listenIn(selectInputIds, 'change');
listenIn(textInputIds, 'keyup');
}())
Your requirements could use some clarification around what happens if both input types have values though.
<html>
<body>
<select name="lstparameters">
<optgroup value="100" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup value="101" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>
</body>
</html>
How to get optgroup values from javascript?I want to get 100 and 101 values.
For those like me wanting to get the optgroup label of the selected option, do this:
document.querySelector('select[name="lstparameters"] option:checked').parentElement.label
Having a select with an id simplifies the selector:
document.querySelector('#lstparameters option:checked').parentElement.label
You can get the optgroup elements and read the value attribute
var values = Array.from(document.querySelectorAll('select[name="lstparameters"] > optgroup')).map(el => el.getAttribute('value'));
alert(values);
//if you want old browser support
var values = [].slice.call(document.querySelectorAll('select[name="lstparameters"] > optgroup')).map(function(el) {
return el.getAttribute('value')
});
alert(values);
<select name="lstparameters">
<optgroup value="100" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup value="101" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>
You can use the .closest() function to determine the selected optgroup
$(function() {
var selected = $('select option:selected');
alert(selected.closest('optgroup').attr('value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<select name="lstparameters">
<optgroup value="100" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab" selected>Saab</option>
</optgroup>
<optgroup value="101" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>
</body>
</html>
#Arun P Johny shows already some ways which are nice and simple.
I just want to provide some other methods.
For really old browsers (< IE9):
var dropdown = document.getElementsByName('lstparameters')[0];
var optgroups = dropdown.getElementsByTagName('optgroup');
var results = [];
for(var i = 0; i < optgroups.length; i++) {
results.push(optgroups[i].getAttribute('value'));
}
alert(results);
And another option with arrow functions and array prototype map:
var results = [].map.call(document.querySelectorAll('select optgroup'), x => { return x.getAttribute('value') });
alert(results);
Update:
To get the value by label you can either add the label to yours query selector (optgroup[label="Swedish Cars"]) or for the for loop method see this:
var dropdown = document.getElementsByName('lstparameters')[0];
var optgroups = dropdown.getElementsByTagName('optgroup');
for(var i = 0; i < optgroups.length; i++) {
if (optgroups[i].getAttribute('label') == 'Swedish Cars') {
alert(optgroups[i].getAttribute('value'));
return;
};
}
alert(results);
I need your help,
I am unsure as to how to go about the following:
If I select the color green into the first select box, I would need the selected option to be automatically selected into the 2nd select box.
How do you accomplish this using just javascript alone.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<span>Category:</span>
<br>
<select id="select1">
<option value=""></option>
<option value="RED">RED</option>
<option value="BLUE">BLUE</option>
<option value="GREEN">GREEN</option>
<option value="YELLOW">YELLOW</option>
</select>
<br>
<span>Your selection was:</span>
<br>
<select id="select2">
<option value=""></option>
<option value="RED">RED</option>
<option value="BLUE">BLUE/option>
<option value="GREEN">GREEN</option>
<option value="YELLOW">YELLOW</option>
</select><b></b>
</body>
</html>
You can iterate through the options until you find the same value:
document.getElementById("select1").onchange = function() {
var selected = this.value;
var select2 = document.getElementById("select2");
//find the index in the second select
for (var i = 0; i < select2.options.length; i++) {
if (select2.options[i].value == selected) {
select2.options[i].selected = true;
}
}
}
Demo: http://jsfiddle.net/HJm7E/
If two select tags have same options:
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
select1.addEventListener('change', function(){
select2.selectedIndex = this.selectedIndex;
});
Fiddle
Note that this simple solution will be wrong for selects that have different options. In this case this will work:
select1.addEventListener('change', function(){
for(var i = 0; i < select2.options.length; i++){
if(select2.options[i].value === this.options[this.selectedIndex].value)
select2.options[i].selected = true;
}
});
Updated fiddle
<!DOCTYPE html>
<html>
<head>
<script>
function doOnload() {
var slt1 = document.getElementById("select1");
var slt2 = document.getElementById("select2");
slt1.onchange = function() {
slt2.options[slt1.selectedIndex].selected = true;
};
}
</script>
</head>
<body onload="doOnload()">
<span>Category:</span>
<br>
<select id="select1">
<option value=""></option>
<option value="RED">RED</option>
<option value="BLUE">GREEN</option>
<option value="GREEN">GREEN</option>
<option value="YELLOW">YELLOW</option>
</select>
<br>
<span>Your selection was:</span>
<br>
<select id="select2">
<option value=""></option>
<option value="RED">RED</option>
<option value="BLUE">GREEN</option>
<option value="GREEN">GREEN</option>
<option value="YELLOW">YELLOW</option>
</select><b></b>
</body>