Displaying Selected Values in Drop-Down List With Multple = On - javascript

I'm trying to display ALL selected values in a drop down list. The code shown below works to display only the first value however I'm struggling on understanding how to get it to display each value that is selected.
function myFunction() {
var x = document.getElementsByName("Car").item(0).value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
<p>Select a new car from the list.</p>
<select name="Car" multiple="on" size="5" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<br>
The car is:
<p id="demo"></p>
https://jsfiddle.net/2gq824q2/12/

Why not use jQuery when you can?
function myFunction() {
var x = $('#car').val()
$('#demo').html("You selected: " + x.join(", "))
}
$('#car').change(function() {
myFunction();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Select a new car from the list.</p>
<select id="car" name="Car" multiple="on" size="5">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<br>
The car is:
<p id="demo"></p>

Here you go: https://jsfiddle.net/2gq824q2/15/
function myFunction() {
var sSelected = '';
[].forEach.call( document.querySelectorAll('#Car :checked') , function(elm){
if(sSelected !== '') sSelected += ', ';
sSelected += elm.value;
})
document.getElementById("demo").innerHTML = "You selected: " + sSelected;
}
<p>Select a new car from the list.</p>
<select id="Car" multiple="on" size="5" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<br>
The car is:
<p id="demo"></p>
I updated the function, and note the select now has an ID.

Related

Javascript select list, show content onchange

The code below outputs:
You selected Audi
How can I change this so that below the select list there is, on loading, my text about Audi which then changes to my text about BMW etc when the corresponding option is selected (using vanilla js not jQuery)?
var mySelect = document.getElementById('mySelect');
mySelect.onchange = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
<select id="mySelect">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<div id="demo"></div>
You can shorten your code:
demo.innerHTML = "You selected: " + mySelect.value;
mySelect.onchange = function() {
demo.innerHTML = "You selected: " + this.value;
}
<select id="mySelect">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<div id="demo"></div>
You can use the onchange event, which gets fired as soon as a new value is selected. Also, remember to properly close tags.
HTML
<select id="select">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
<div id="div"></div>
JavaScript
function onValueChanged (e)
{
document.getElementById('div').innerHTML = `You text about ${e.target.value}...`;
}
document.getElementById('select').onchange = onValueChanged;
Here's the fiddle.
This worked for me
var mySelect = document.getElementById('mySelect');
mySelect.addEventListener('change', (e) => {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
})
<select id="mySelect">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<p id="demo"></p>
You just need to add the line on the beginning.
In order to maintain the DRY principle, I used an external function to update the demo div:
function updateDemo() {
var mySelect = document.getElementById('mySelect');
document.getElementById("demo").innerHTML = `You selected: ${mySelect.value}`
}
// Just add this line:
updateDemo();
mySelect.onchange = function() {
updateDemo();
}
<select id="mySelect">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<div id="demo"></div>
Well first of all have a look here :
https://www.w3schools.com/tags/tag_option.asp
the option tag have a start and closing tag as well :)
Plus there is type error see below :
"message": "TypeError: document.getElementById(...) is null",
Here is a sample snippet
(function () {
'use strict';
document.querySelector('#mySelect').addEventListener('change', function (event) {
var x = event.target.value;
document.querySelector("#demo").innerHTML = "You selected: " + x;
})
})();
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8" />
</head>
<body>
<select id="mySelect">
<option value="Audi">Audi </option
><option value="BMW">BMW </option
><option value="Mercedes">Mercedes </option
><option value="Volvo">Volvo </option>
</select>
<div id="demo"></div>
</body>
</html>

InnerHTML Output for Selected Values

My script works with the <select> to update a hidden paragraph on the template based on the values selected. This is working fine but my request here is to set conditionals for 2 select values for each car. For example, if I select Audi + Red I want to show, say: "Beautiful Car". For BMW + Black: "Black BMW for sale".
Basically I want to create an output based on the values selected from both <select> fields and I want to create 8 unique values for each car brand and color.
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<select id="Variants">
<option value="Black"> Black
<option value="Red">Red
</select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
<script>
function myFunction() {
let messages = {
Audi: 'RandomData1',
BMW: 'RandomData2',
Mercedes: 'RandomData3',
Volvo: 'RAndomData4'
}
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = `${messages[x]}`;
}
</script>
</body>
</html>
I think this is what you are trying to achieve. The solution was to generate objects matching the drop-down values for the color and manufacturer.
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<select id="Variants" onchange="myFunction()">
<option value="Black"> Black
<option value="Red">Red
</select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
<script>
function myFunction() {
let messages = {
"Audi":{"Black":"audi color black","Red":"audi color red"},
"BMW":{"Black":"BMW color black","Red":"BMW color red"},
"Mercedes":{"Black":"Mercedes color black","Red":"Mercedes color red"},
"Volvo":{"Black":"Volvo color black","Red":"Volvo color red"}};
var x = document.getElementById("mySelect").value;
var y = document.getElementById("Variants").value;
document.getElementById("demo").innerHTML = messages[x][y];
}
</script>
</body>
</html>
function myFunction() {
let messages = {
black0: 'Black Audi',
red0: 'Red Audi',
black1: 'Black BMW',
red1: 'Red BMW',
black2: 'Black Mercedes',
red2: 'Red Mercedes',
black3: 'Black Volvo',
red3: 'Red Volvo'
};
var car = document.getElementById("mySelect").value;
var color = document.getElementById("Variants").value;
document.getElementById("demo").innerHTML = `${messages[color+car]}`;
}
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="0">Audi
<option value="1">BMW
<option value="2">Mercedes
<option value="3">Volvo
</select>
<select id="Variants" onchange="myFunction()">
<option value="black"> Black
<option value="red">Red
</select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
</body>

Second dropdown value is not changing if I doesn't change my first dropdown

I am trying to show a table of reviews by taking the value of two dropdowns. When I was having one dropdown(positive, negative etc) that works fine but when I introduce another dropdown(food, drinks etc) it is not working.
It only works when I change the first dropdown and second dropdown but if I kept the first dropdown unchanged then it's not working
I tried by adding onchange method to the second dropdown. I just started with Javascript so not much idea about what to try.
function printResult(form) {
var output = {
{
output | safe
}
};
var sel = form.list;
var sel2 = form.list2;
var selectedVal = sel.options[sel.selectedIndex].value;
var selectedVal2 = sel2.options[sel.selectedIndex].value;
//document.getElementById("showResult").innerText = "Your number is: " + selectedVal;
//console.log(output);
document.getElementById("showResult").innerText = "Your number is: " + selectedVal2;
}
<form action="dropdown" onSubmit="return printResult(this);">
<label for="sentiment">Sentiment</label>
<div class="styled-select blue semi-square">
<select name="list">
<option value="all">All</option>
<option value="positive">Positive</option>
<option value="negative">Negative</option>
<option value="neutral">Neutral</option>
</select>
</div>
<div>
<select name="list2" onChange="printResult()">
<option value="menu">Menu Range</option>
<option value="food">Food</option>
<option value="drinks">Drinks</option>
<option value="desserts">Desserts</option>
</select>
</div>
<input type="submit" value="Filter">
<span id="showResult"></span>
</form>
You need to pass the form on the change too and return false to not submit the form:
function printResult(form) {
var sel = form.list;
var sel2 = form.list2;
var selectedVal = sel.value;
var selectedVal2 = sel2.value;
document.getElementById("showResult").innerText = "Your number is: " + selectedVal2;
return false;
}
<form action="dropdown" onSubmit="return printResult(this);">
<label for="sentiment">Sentiment</label>
<div class="styled-select blue semi-square">
<select name="list">
<option value="all">All</option>
<option value="positive">Positive</option>
<option value="negative">Negative</option>
<option value="neutral">Neutral</option>
</select>
</div>
<div>
<select name="list2" onChange="printResult(this.form)">
<option value="menu">Menu Range</option>
<option value="food">Food</option>
<option value="drinks">Drinks</option>
<option value="desserts">Desserts</option>
</select>
</div>
<input type="submit" value="Filter">
<span id="showResult"></span>
</form>
Perhaps you wanted this instead
window.addEventListener("load", function() {
document.getElementById("form1").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
var sel = this.list;
var sel2 = this.list2;
var selectedVal = sel.value;
var selectedVal2 = sel2.value;
document.getElementById("showResult").innerText = (selectedVal && selectedVal2) ? selectedVal + ":" + selectedVal2 : "Please select both";
});
});
<form action="dropdown" id="form1">
<label for="sentiment">Sentiment</label>
<div class="styled-select blue semi-square">
<select name="list">
<option value="">All</option>
<option value="positive">Positive</option>
<option value="negative">Negative</option>
<option value="neutral">Neutral</option>
</select>
</div>
<div>
<select name="list2">
<option value="">Menu Range</option>
<option value="food">Food</option>
<option value="drinks">Drinks</option>
<option value="desserts">Desserts</option>
</select>
</div>
<input type="submit" value="Filter">
<span id="showResult"></span>
</form>

Using IF statements in a form to narrow choices down

I basically want to limit my choices in my form so that when a car is chosen as well as the transmission only certain colors may appear. I have created the form. The problem is creating the code in the Javascript file. I don't know how to make it so that if Car 1 is chosen as well as Automatic then for example only Black and blue appear as options. Im relatively new to coding and any help would be appreciated.
Thanks
HTML
<script src="Script\configurator.js" type="text/javascript"></script>
<form name="CarConfigurator">
<select name="Car_make" onchange="Transmission(this.value);">
<option value=" " selected="selected">None</option>
<option value="1">Audi RS6</option>
<option value="2">BMW M4</option>
<option value="3">Mercedes C63 AMG</option>
</select>
<br>
<br>
<select name="A_M" >
<option value="" selected="selected">None</option>
<option value="1" selected="selected">Automatic</option>
<option value="2" selected="selected">Manual</option>
</select>
<br>
<br>
<select name="Color">
<option value="" selected="selected">None</option>
<option value="1">Black</option>
<option value="2">Blue</option>
<option value="3">Red</option>
<option value="4">White</option>
<option value="5">Green</option>
</select>
</form>
Javascript
function Transmission(Car) {
var make = document.CarConfigurator.A_M;
make.options.length = 0;
if (Car == "1") {
make.options[make.options.length] = new Option('Automatic','1');
make.options[make.options.length] = new Option ('Manual','2');
}
if (Car =="2" ) {
make.options[make.options.length] = new Option('Manual','2');
}
if (Car == "3") {
make.options[make.options.length] = new Option('Automatic','3');
}
}
Is this what you want:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form name="CarConfigurator">
<select name="Car_make" onchange="Transmission();">
<option value=" " selected="selected">None</option>
<option value="1">Audi RS6</option>
<option value="2">BMW M4</option>
<option value="3">Mercedes C63 AMG</option>
</select>
<br>
<br>
<select name="A_M" onchange="Transmission();">
<option value="" selected="selected">None</option>
<option value="1" selected="selected">Automatic</option>
<option value="2" selected="selected">Manual</option>
</select>
<br>
<br>
<select name="Color" onchange="ChoicesMade();">
<option value="" selected="selected">None</option>
<option value="1">Black</option>
<option value="2">Blue</option>
<option value="3">Red</option>
<option value="4">White</option>
<option value="5">Green</option>
</select>
<div id="imageContainer" style="display: none;"><img src="http://buyersguide.caranddriver.com/media/assets/submodel/6873.jpg" /></div>
</form>
<script type="text/javascript">
function Transmission() {
var Car = document.CarConfigurator.Car_make.value;
var make = document.CarConfigurator.A_M.value;
var color = document.CarConfigurator.Color;
color.options.length = 0;
if (Car == "1" && make == '1') {
color.options.add(new Option('Black', '1'));
color.options.add(new Option('Blue', '2'));
}
else if(Car == '2' && make == '1')
{
color.options.add(new Option('Red', '3'));
color.options.add(new Option('White', '4'));
}
ChoicesMade();
}
function ChoicesMade()
{
var form = document.CarConfigurator;
var car = form.Car_make.value;
var make = form.A_M.value;
var color = form.Color.value;
if(car != ' ' && make != '' && color != '')
{
var imageContainer = document.querySelector('#imageContainer');
imageContainer.style.display = 'block';
}
}
</script>
</body>
</html>
You can use objects in JavaScript and then loop through each array in object to change options. For example
var cars = {
"Audi_RS6":{
"name":"Audi RS6",
"Automatic":["color_1","color_2"],
"Manual":["color_1","color_2"]
},
"BMW_M4":{
"name":"BMW M4",
"Manual":["color_1","color_2"]
},
"Mercedes_C63_AMG":{
"name":"Mercedes C63 AMG",
"Automatic":["color_1","color_2"]
}
};
values can be accessed like this
var result = cars.Audi_RS6.Manual[1];
Here you go Duncher, this code does exactly what you want
<!DOCTYPE html>
<html><head>
<title></title>
</head>
<body>
<form name="CarConfigurator">
<select id="car" name="Car_make">
<option value="" selected="selected">Which car?</option>
<option value="car1">Audi RS6</option>
<option value="car2">BMW M4</option>
<option value="car3">Mercedes C63 AMG</option>
</select>
<br>
<br>
<select id="trans" name="A_M">
<option value="" selected="selected">What trans?</option>
<option value="auto">Automatic</option>
<option value="man">Manual</option>
</select>
<br>
<br>
<select id="color" name="Color">
<option value="" selected="selected">What Color?</option>
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="white">White</option>
<option value="green">Green</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script src="configurator.js"></script>
</body>
</html>
And the JavaScript:
$("#car").change(function () {
transmission();
});
$("#trans").change(function () {
transmission();
});
function transmission() {
if ($("#car").val() == "car1" && $("#trans").val() == "auto") {
$("option[value$='red']").hide();
$("option[value$='white']").hide();
$("option[value$='green']").hide();
} else {
$("option[value$='red']").show();
$("option[value$='white']").show();
$("option[value$='green']").show();
}
}
You will have to make a few tweaks to get your other car & trans combinations working how you want them to (i.e. displaying only the colors you want) by adding more if else statements in the transmission() method but this should get you on your way. This is using jQuery by the way.
Screen shot

Add data into a Select

I have this select; to select countries and add to a new select multiple with a limit of 5 countries, but I just want to add 1 country by select or more countries if i do a multiple select.
My mistake is in my function addC(), when I want to add more than 1 country in my select, it add the several countries in 1 option tag like this:
<option>South KoreaUSAJapan</option>
What I can modify to display the following way if i do a multiple select?:
<option>South Korea</option>
<option>USA</option>
<option>Japan</option>
My code:http://jsbin.com/osesem/4/edit
function addC() {
if ($("#agregarProvincia option").length < 5) {
var newC = ($("#countries option:selected").text());
$("#addCountry").append("<option>" + newC + "</option>");
}
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<label for="provincia2"><b>¿Country?</b></label><br>
<span>
<select multiple="multiple" size="5" id="countries">
<option value="1">South Korea</option>
<option value="2">USA</option>
<option value="2">Japan</option>
<option value="3">Italy</option>
<option value="4">Spain</option>
<option value="5">Mexico</option>
<option value="6">England</option>
<option value="7">Phillipins</option>
<option value="8">Portugal</option>
<option value="9">France</option>
<option value="10">Germany</option>
<option value="11">Hong Kong</option>
<option value="12">New Zeland</option>
<option value="13">Ireland</option>
<option value="14">Panama</option>
<option value="15">Norwey</option>
<option value="16">Sweeden</option>
<option value="17">India</option>
<option value="18">Morroco</option>
<option value="19">Russia</option>
<option value="20">China</option>
</select>
</span>
<div class="addremover">
<input class="add" type="button" onclick="addC()" value="Addd »" />
<br/>
</div>
<span>
<select id="addCountry" multiple="multiple" size="5">
</select>
</span>
use each function to loop through the text and append it..
try this
function addC() {
if ($("#agregarProvincia option").length < 5) {
var newC = ($("#countries option:selected"));
newC.each(function(){
$("#addCountry").append("<option>" + $(this).text() + "</option>");
})
}
}
JSbin here
Or just clone the selected <option>'s
function addC() {
if ($('#countries option:selected').size() < 5)
{
$('#addCountry').append($('#countries option:selected').clone());
}
else
{
alert('you can only select 5');
}
}

Categories