How to get latest value selected from multiselect dropdown - javascript

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>

Related

How to change select's option based on a selected option's value?

I have select tag below:
<select name="selID" id="selID" data-mini="true"">
<option value="1" selected="selected">Tithes</option>
<option value="2">Offering</option>
<option value="3">Designated</option>
<option class="selOptAddMore" value="0">Add More...</option>
</select>
I want to change value when one of the options is selected except for "Add More..."
Sorry I'm a newbie. Thanks in advance.
You can try this:
The HTML:
<body>
Result: <p id="result"></p>
<select name="selID" id="selID" data-mini="true" onchange="test()">
<option value="1" selected="selected">Tithes</option>
<option value="2">Offering</option>
<option value="3">Designated</option>
<option class="selOptAddMore" value="0">Add More...</option>
</select>
<script src="test.js"></script>
</body>
test.js:
function test() {
let listVal = document.getElementById("selID").value;
if (listVal != "0") {
document.getElementById("result").innerHTML = listVal;
}
else {
listVal = 1; // this is value for "Tithes"
document.getElementById("selID").value = listVal;
document.getElementById("result").innerHTML = listVal;
}
}

Showing select options on different select options

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>

Javascript Show Multiple select option value

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>

Using Javascript to check form elements and enabling/disabling the search button

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.

Javascript code is not working

How can I amend the code so that when I select a option from the first drop down menu the second drop down menu becomes editable otherwise the second drop-down menu should be read only, and if the option in the first drop down menu is "default" then the second drop down menu should be read only.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function mySecondFunction() {
document.getElementById("mySelection").disabled = false;
}
</script>
</head>
<body>
<form action="">
<select name="cars" onload="mySecondFunction()">
<option value="default">default</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br>
<select disabled name="cars" id="mySelection">
<option value="Action1">Volvo</option>
<option value="Action2">Saab</option>
<option value="Action3">Fiat</option>
<option value="Action4">Audi</option>
</select>
</form>
</body>
</html>
Look at the capitals:
document.getElementById("MySelection").disabled = false;
<select disabled name="cars" id="mySelection">
The first is with "M" and the seccond with "m"
You have misspelled MySelection with mySelection
In the JS you have document.getElementById("MySelection") // notice the uppercase M
and in the HTML you have id="mySelection"
Also set the second select to false when the window loads and add a onChange event to the first select that will set the second event to enabled/true... it this what you want?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function(){
document.getElementById("mySelection").disabled = true;
};
function mySecondFunction() {
document.getElementById("mySelection").disabled = false;
}
</script>
</head>
<body>
<form action="">
<select name="cars" onchange="mySecondFunction()">
<option value="default">default</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br>
<select name="cars" id="mySelection">
<option value="Action1">Volvo</option>
<option value="Action2">Saab</option>
<option value="Action3">Fiat</option>
<option value="Action4">Audi</option>
</select>
</form>
</body>
</html>
You may want to set the second select back to disabled if the user selects 'default' in the first menu after changing the value
JavaScript selectors are case sensitive. Your mistake is at mySelection id:
document.getElementById("MySelection").disabled = false;
<select disabled name="cars" id="mySelection">
You must use that inside body tag .
fiddle
<head>
</head>
<body onload="mySecondFunction()">
<form action="">
<select name="cars" >
<option value="default">default</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br>
<select disabled name="cars" id="mySelection">
<option value="Action1">Volvo</option>
<option value="Action2">Saab</option>
<option value="Action3">Fiat</option>
<option value="Action4">Audi</option>
</select>
</form>
</body>
<script type="text/javascript">
function mySecondFunction() {
alert("aaa");
document.getElementById("mySelection").disabled = false;
}
</script>
</html>
As others pointed out you mispelled the id of the second <select> but also you used the wrong event, onchange is what you want instead of onload.
function mySecondFunction() {
document.getElementById('mySelection').disabled = false;
}
<form action="">
<select name="cars" onchange="mySecondFunction();">
<option value="default">default</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br />
<select disabled="disabled" name="cars" id="mySelection">
<option value="Action1">Volvo</option>
<option value="Action2">Saab</option>
<option value="Action3">Fiat</option>
<option value="Action4">Audi</option>
</select>
</form>
But consider using jQuery and attach your events in javascript instead of having them stored in html.
Try this:
Replace
document.getElementById("mySelection").disabled = false;
with this
document.getElementById("mySelection").removeAttribute('disabled');
Also, you may want to change
onload="mySecondFunction()"
with this:
onchange="mySecondFunction()"
Hope this helps.
Change onload to onchange.
<select name="cars" onchange="mySecondFunction();">
if you want to remove the disable in a specific value like (Saab)
See fiddle
note: put the script in b4 the head tag
function mySecondFunction()
{
var ddl = document.getElementById("1");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "saab")
{
document.getElementById("mySelection").disabled = false;
}else {
document.getElementById("mySelection").disabled = true;
}
}
<form action="">
<select id="1" name="cars" onchange="mySecondFunction()">
<option value="default">default</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br />
<select disabled="disabled" name="cars" id="mySelection">
<option value="Action1">Volvo</option>
<option value="Action2">Saab</option>
<option value="Action3">Fiat</option>
<option value="Action4">Audi</option>
</select>
</form>
UPDATE
See fiddle
function mySecondFunction()
{
var ddl = document.getElementById("1");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "default")
{
document.getElementById("mySelection").disabled = true;
}else {
document.getElementById("mySelection").disabled = false;
}
}

Categories

Resources