This question already has answers here:
How to get all selected values of a multiple select box?
(28 answers)
Closed 5 years ago.
I'm still a beginner hence this is difficult, but how do I display the options I selected into an alert box. So it would be "You selected (value), (value), (value)".
This is my select list
<form id='form1'>
<select id="options" multiple >
<option value="action">Action</option>
<option value="animation">Animation</option>
<option value="children">Children</option>
<option value="classics">Classics</option>
<option value="comedy">Comedy</option>
<option value="documentary">Documentary</option>
<option value="drama">Drama</option>
<option value="family">Family</option>
<option value="foreign">Foreign</option>
<option value="games">Games</option>
<option value="horror">Horror</option>
<option value="music">Music</option>
<option value="new">New</option>
<option value="scifi">Sci-Fi</option>
<option value="sports">Sports</option>
<option value="travel">Travel</option>
</select>
</form>
Should I add a button. But what I'm struggling with is the javascript.
The easiest way to access selected elements of a select tag is with the "selectedOptions" property.
I would do it this way:
var form = document.getElementById('form1');
form.addEventListener('submit', function () {
var select = form.querySelector('#options'),
options = select.selectedOptions,
values = [];
for (var i = options.length - 1; i >= 0; i--) {
values.push(options[i].value);
}
alert('You selected: ' + values.join(', '));
}, false);
Try something like this:
function selectedValues()
{
var x=document.getElementById("options");
var selectedValues= '';
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
selectedValues += x.options[i].value + ", ";
}
}
alert("You selected: "+ selectedValues.slice(0, -2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id='form1'>
<select id="options" multiple onchange="selectedValues()">
<option value="action">Action</option>
<option value="animation">Animation</option>
<option value="children">Children</option>
<option value="classics">Classics</option>
<option value="comedy">Comedy</option>
<option value="documentary">Documentary</option>
<option value="drama">Drama</option>
<option value="family">Family</option>
<option value="foreign">Foreign</option>
<option value="games">Games</option>
<option value="horror">Horror</option>
<option value="music">Music</option>
<option value="new">New</option>
<option value="scifi">Sci-Fi</option>
<option value="sports">Sports</option>
<option value="travel">Travel</option>
</select>
</form>
Related
I'm setting up a new form on my site, and I'm using some code I found here (Vehicle drop down selector). However, I'm using this code within a form, and once the form is submitted, the values for make/model aren't changed to their respective names, instead showing their form values. Being a complete JS noob, how would I go about changing the values submitted from values to make/model names?
$(document).ready(function() {
var $make = $('#make'),
$model = $('#model'),
$options = $model.find('option');
$make.on('change', function() {
$model.html($options.filter('[value="' + this.value + '"]'));
$model.trigger('change');
}).trigger('change');
var $model = $('#model'),
$year = $('#year'),
$yearOptions = $year.find('option');
$model.on('change', function() {
$year.html($yearOptions.filter('[value="' + this.value + '"]'));
$year.trigger('change');
}).trigger('change');
var $year = $('#year'),
$identifier = $('#identifier'),
$identifierOptions = $identifier.find('option');
$year.on('change', function() {
var filteredIdetifiers = $identifierOptions.filter('[value="' + this.value + '"]');
debugger
if (!($("#make").val() == 3 && $("#model option:selected").text() == 'Falcon')) {
filteredIdetifiers = filteredIdetifiers.filter(function(i, e) {
return e.value !== '3'
});
}
$identifier.html(filteredIdetifiers);
$identifier.trigger('change');
}).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Vehicle Brand Selector List -->
<select name="make" id="make">
<option value="0">Make</option>
<option value="1">BMW</option>
<option value="2">Daewoo</option>
<option value="3">Ford</option>
<option value="4">Holden</option>
<option value="5">Honda</option>
<option value="6">Hyundai</option>
<option value="7">Isuzu</option>
<option value="8">Kia</option>
<option value="9">Lexus</option>
<option value="10">Mazda</option>
<option value="11">Mitsubishi</option>
<option value="12">Nissan</option>
<option value="13">Peugeot</option>
<option value="14">Subaru</option>
<option value="15">Suzuki</option>
<option value="16">Toyota</option>
<option value="17">Volkswagen</option>
</select>
<!-- Vehicle Model List -->
<select name="model" id="model">
<option value="0">Model</option>
<option class="318i" value="1">318i</option>
<option class="lanos" value="2">Lanos</option>
<option class="courier" value="3">Courier</option>
<option class="falcon" value="3">Falcon</option>
<option class="festiva" value="3">Festiva</option>
<option class="fiesta" value="3">Fiesta</option>
<option class="focus" value="3">Focus</option>
<option class="laser" value="3">Laser</option>
<option class="ranger" value="3">Ranger</option>
<option class="territory" value="3">Territory</option>
<option class="astra" value="4">Astra</option>
<option class="barina" value="4">Barina</option>
<option class="captiva" value="4">Captiva</option>
<option class="colorado" value="4">Colorado</option>
<option class="commodore" value="4">Commodore</option>
<option class="cruze" value="4">Cruze</option>
<option class="rodeo" value="4">Rodeo</option>
<option class="viva" value="4">Viva</option>
</select>
<!-- Vehicle Year List -->
<select name="year" id="year">
<option value="0">Year</option>
<option value="1">1998</option>
<option value="1">1999</option>
<option value="1">2000</option>
<option value="1">2001</option>
<option value="1">2002</option>
<option value="1">2003</option>
<option value="1">2004</option>
<option value="1">2005</option>
<option value="2">1997</option>
<option value="2">1998</option>
<option value="2">1999</option>
<option value="2">2000</option>
<option value="2">2001</option>
<option value="2">2002</option>
<option value="2">2003</option>
<option value="3">1991-1999</option>
<option value="4">1997-2007</option>
<option value="5">1997-2007</option>
<option value="3">2002</option>
<option value="3">2003</option>
<option value="3">2004</option>
<option value="3">2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
</select>
<!-- Vehicle Identity List -->
<select name="identifier" id="identifier">
<option value="0">Type</option>
<option class="E46" value="1">E46</option>
<option class="1997-2003" value="2">N/A</option>
<option class="1997-2007" value="4">N/A</option>
<option class="1997-2007" value="5">N/A</option>
<option class="5041618" value="3">BA</option>
<option class="1997-2005" value="3">AU</option>
<option class="1997-2005" value="3">AU2</option>
<option class="1997-2005" value="4">N/A</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
</select>
In every <option> tag there is an attribute called value. This value attribute is what is returned at as the value of the dropdown when that option is selected. Seems like in the code you found they are all simply set to numbers. You can set them to be whatever you want though:
<option value="Ford">Ford</option>
<option class="focus" value="Focus">Focus</option>
FIXING DYNAMIC OPTIONS
I see that modifying the values directly affect how the dynamic options are displayed. For example the value attribute of the car model dropdown is used to filter the car make dropdown by only displaying options with the same value. Instead of using the model dropdown's value attributes to compare with make, we can add a new data- attribute called data-make and filter the model dropdown based on that instead. This allows you to freely modify the value attribute in model. The example code below shows this. You would need to modify your JS so model affects year, and year affects identifier in the same way.
$(document).ready(function() {
var $make = $('#make'),
$model = $('#model'),
$options = $model.find('option');
$make.on('change', function() {
// We now filter model using the data-make attribute, not value
$model.html($options.filter('[data-make="' + this.value + '"]'));
$model.trigger('change');
}).trigger('change');
$('#carForm').submit(function(e) {
e.preventDefault();
let formData = $(this).serializeArray();
let data = {};
for (let i = 0; i < formData.length; i++) {
data[formData[i].name] = formData[i].value;
}
alert('Make: ' + data.make + '\nModel: ' + data.model);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="carForm">
<select name="make" id="make">
<option value="0">Make</option>
<option value="BMW">BMW</option> <!-- These values are now make names -->
<option value="Daewoo">Daewoo</option>
<option value="Ford">Ford</option>
</select>
<!-- Vehicle Model List -->
<!-- Notice the new "data-make" attributes for each -->
<select name="model" id="model">
<option value="0">Model</option>
<option class="318i" value="318i" data-make="BMW">318i</option>
<option class="lanos" value="Lanos" data-make="Daewoo">Lanos</option>
<option class="courier" value="Courier" data-make="Ford">Courier</option>
<option class="falcon" value="Falcon" data-make="Ford">Falcon</option>
<option class="festiva" value="Festiva" data-make="Ford">Festiva</option>
<option class="fiesta" value="Fiesta" data-make="Ford">Fiesta</option>
<option class="focus" value="Focus" data-make="Ford">Focus</option>
</select>
<button type="submit">Submit</button>
</form>
You can get the selected option text like this.
$('#form').submit(function(e) {
e.preventDefault();
var make = $make.find(':selected').text();
}
But it would be good practice to set the value you expect to return as the option value and use a data attribute or class to handle the filtering logic.
$(document).ready(function () {
var presentyear = new Date().getFullYear();
for(y = 1995; y <= presentyear; y++)
{
var optn = document.createElement("option");
optn.text = y;
optn.value = y;
document.getElementById('year10').options.add(optn);
}
});
<select id="year10">
<option>select year</option>
//all the values will be dynamically added as called by function in js
</select>
<select id="gap">
<option value="0">Select Number of Years</option>
<option value="1">1 year</option>
<option value="2">2 years</option>
<option value="3">3 years</option>
<option value="4">4 years</option>
<option value="5">5 years</option>
</select>
<select id="year12">
<option id="calvalue"> </option>
</select>
I want to save selected values from two select tags and show the sum in a separate third select dropdown.
As in the snippet above, I have three select tags, the javascript code fills the options for 'year10' select from 1995 to 2017.
The 'gap' select have 5 values.
Now, i want to add the selected values of 'year10' and 'gap' and show in the single option (with id='calvalue') in 'year12' select tag.
Also, when i change the values in either first two selects, the summed value in year12 must change with it.
How to do this?
Any help is appreciated
To achieve this you just need to add a change event handler to both of the selects which reads the values and adds them together.
Note that putting the result in another option of a select is a little odd. I'd suggest using a readonly text box instead, something like this:
$(function() {
var presentyear = new Date().getFullYear(), options = '';
for (y = 1995; y <= presentyear; y++) {
options += '<option value="' + y + '">' + y + '</option>';
}
$('#year10').append(options);
$('#year10, #gap').change(function() {
var year = parseInt($('#year10').val(), 10) || 0;
var gap = parseInt($('#gap').val(), 10) || 0;
$('#year12').val(!year ? '' : year + gap);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="year10">
<option>select year</option>
</select>
<select id="gap">
<option value="0">Select Number of Years</option>
<option value="1">1 year</option>
<option value="2">2 years</option>
<option value="3">3 years</option>
<option value="4">4 years</option>
<option value="5">5 years</option>
</select>
<input type="text" readonly="readonly" id="year12">
if you're ok with jquery... then
<select id="num1" onchange="addThem()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="num2" onchange="addThem()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="res">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<script>
function addThem(){
var num1 = $("#num1").val();
var num2 = $("#num2").val();
$("#res").val(Number(num1) +Number(num2));
}
</script>
this Plunker sample i did should help you out
function jsFunction(){
var myselect = document.getElementById("selectOpt");
$("#secondselectbox").val(myselect);
}
<select onChange="jsFunction()" id="selectOpt">
<option value="1" onclick="jsFunction()">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="secondselectbox">
</select>
In this code After value selection you can do any new function(another select tag).
You will have to work on the specifics your self, but this should get you started.
let nextOption = {first: 1, seccond: 1}
function selected(selector, option) {
if (selector === 'first') {
nextOption.first = parseInt(option.value);
}
else if (selector === 'seccond') {
nextOption.seccond = parseInt(option.value);
}
let newOption = document.createElement("option");
newOption.text = nextOption.first + nextOption.seccond;
document.getElementById('final').add(newOption);
}
selected();
<select onClick="selected('first', this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select onClick="selected('seccond', this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="final">
</select>
When the Primary dropdown changes, I want the other dropdown to change accordingly.
But I dont know why only the 1st Other dropdown is working while the 2nd fails to change its value accordingly. I
m aware that if I change the name of the 2nd dropdown to the same as the 1st dropdown it will work.
But as they are different fields that are to be saved in the db, so the names have to be different.
Any solution would be appreciated. Many thanks.
function setDropDown() {
var index_name =
document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.getElementsByName('Qualifications');
for (i = 0; i < others.length; i++)
others[i].selectedIndex = index_name;
var others2 = document.getElementsByName('Qualifications2');
for (i = 0; i < others2.length; i++)
others2[i].selectedIndex = index_name2;
}
Primary dropdown<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select> other dropdown
<select id="Qualifications" name="Qualifications">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select> other dropdown2
<select id="Qualifications2" name="Qualifications2">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
Add a css class to your secondary drop downs and use document.querySelectorAll to get them all at once.
Then you can use a single loop to update their selectedIndex.
function setDropDown() {
var index_name =
document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.querySelectorAll('.secondary');
for (var i = 0; i < others.length; i++) {
others[i].selectedIndex = index_name;
}
}
div {
padding: 15px;
}
<div><b>Primary dropdown:</b>
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</div>
<div>
<b>Other dropdown 1</b>:
<select class='secondary' id="Qualifications" name="Qualifications">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select></div>
<div> <b>Other dropdown 1</b>:
<select class='secondary' id="Qualifications2" name="Qualifications2">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</div>
So it turns out i haven't defined sth in my code, thanks for pointing that out #Tiny Giant
function setDropDown() {
var index_name =
document.getElementsByName('ForceSelection')[0].selectedIndex;
var index_name2 =
document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.getElementsByName('Qualifications');
for (i = 0; i < others.length; i++)
others[i].selectedIndex = index_name;
var others2 = document.getElementsByName('Qualifications2');
for (j = 0; j < others2.length; j++)
others2[j].selectedIndex = index_name2;
}
Primary dropdown<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select> other dropdown
<select id="Qualifications" name="Qualifications">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select> other dropdown2
<select id="Qualifications2" name="Qualifications2">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
I'm searching and searching and can not find anything exactly what I need.
So I need javascript, that will select option from dropdown, but not by the option value number, but name.
I have:
<select class="aa" id="local" name="local">
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
So I need to select • Jawor by name, not by id - it's the most important. How do I make it work?
For you is it like;
var options = document.getElementsByClassName("aa")[0].options,
name ="Jawor";
for(i = 0; i < options.length; i++){
if(options[i].text.indexOf(name) > -1){
options[i].selected = true;
break;
}
}
<select class="aa" id="local" name="local">
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
U need to Use onChange Event Handler ... for example
<select onchange="showSelected()">
Then write your script ...
<script>
function showSelected(){
var s=document.getElementById('local'); //refers to that select with all options
var selectText=s.options[s.selectedIndex].text // takes the one which the user will select
alert(selectText) //Showing the text selected ...
}
</script>
Rest of your code is okay !
<select class="aa" id="local" name="local" onchange='showSelected'()>
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
Using jquery here. You can use the following function:
function selectFromDropdown(selector, text) {
$(selector).find('option').each(function() {
if ($(this).text() == text) {
$(selector).val($(this).val());
}
})
}
A demo:
function selectFromDropdown(selector, text) {
$(selector).find('option').each(function() {
if ($(this).text() == text) {
$(selector).val($(this).val());
return false;
}
})
}
//use the function
setTimeout(function() {
selectFromDropdown('#local', '• Dzierżoniów')
}, 1000)
setTimeout(function() {
selectFromDropdown('#local', '• Jawor')
}, 4000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="aa" id="local" name="local">
<option value="">Select</option>
<option value="0">Cała Polska</option>
<option value="1">Dolnośląskie</option>
<option value="100">• Bolesławiec</option>
<option value="101">• Dzierżoniów</option>
<option value="102">• Głogów</option>
<option value="103">• Góra</option>
<option value="104">• Jawor</option>
<option value="105">• Jelenia Góra</option>
</select>
for chrome console use this
document.getElementById("id").selectedIndex = '3'; or
document.getElementById('id').value = 'BA';
I have two <select> elements with different IDs.
When the user selects a value from the first select box, I want the second select box to only display connected values.
My code:
<select id="ExtraField_1" name="ExtraField_1">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
<option value="4">test4</option>
<option value="5">test5</option>
<option value="6">test6</option>
<option value="7">test7</option>
<option value="8">test8</option>
<option value="9">test9</option>
<option value="10">test10</option>
<option value="11">test11</option>
<option value="12">test12</option>
</select>
<select id="ExtraField_2" name="ExtraField_2">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
<option value="4">test4</option>
<option value="5">test5</option>
<option value="6">test6</option>
<option value="7">test7</option>
<option value="8">test8</option>
<option value="9">test9</option>
<option value="10">test10</option>
<option value="11">test11</option>
<option value="12">test12</option>
<option value="13">test13</option>
<option value="14">test14</option>
<option value="15">test15</option>
<option value="16">test16</option>
<option value="17">test17</option>
<option value="18">test18</option>
<option value="19">test19</option>
<option value="20">test20</option>
</select>
So when user selects "test1" from first select boxm he will see only "test2", "test3" and "test4" on the second select box; "test2" from first will show "test6", "test7" and "test8" in the second box.
How can I use JavaScript to resolve this problem?
If you can use jQuery then you can always just clear and append the options to the second select.
$('#ExtraField_1').change(function(){
$('#ExtraField_2').find('option').remove()
if($(this).val() == '1'){
$('#ExtraField_2').append($("<option </option>").attr('value','2').text('test2'));
$('#ExtraField_2').append($("<option></option>").attr('value','3').text('test3'));
$('#ExtraField_2').append($("<option></option>").attr('value','4').text('test4'));
}
if($(this).val() == '2'){
$('#ExtraField_2').append($("<option></option>").attr('value','5').text('test5'));
$('#ExtraField_2').append($("<option></option>").attr('value','6').text('test6'));
$('#ExtraField_2').append($("<option></option>").attr('value','7').text('test7'));
}
});
http://jsfiddle.net/8XVuv/2/
using only javascript is a bit more complicated but I would still take the same approach.
function createOption(otext,oValue){
var newOption = document.createElement('option');
newOption.text = otext;
newOption.value = oValue;
return newOption;
}
function clearSelect(theSelect){
for(var i = 0;i <= theSelect.options.length+1;i++)
{
theSelect.remove();
}
}
function onSelect(theSelect){
var nextSelect = document.getElementById('ExtraField_2');
clearSelect(nextSelect);
var selected = theSelect.options[theSelect.selectedIndex];
if(selected.value == 1){
nextSelect.add(createOption('test2','2'));
nextSelect.add(createOption('test3','3'));
nextSelect.add(createOption('test4','4'));
}
if(selected.value == 2){
nextSelect.add(createOption('test5','5'));
nextSelect.add(createOption('test6','6'));
nextSelect.add(createOption('test7','7'));
}
}
with html:
<select id="ExtraField_1" name="ExtraField_1" onchange="javascript: onSelect(this);" >
<option value="0">Select a test..</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
<option value="4">test4</option>
<option value="5">test5</option>
<option value="6">test6</option>
<option value="7">test7</option>
<option value="8">test8</option>
<option value="9">test9</option>
<option value="10">test10</option>
<option value="11">test11</option>
<option value="12">test12</option>
</select>
<select id="ExtraField_2" name="ExtraField_2">
<option value="0">Select from the left</option>
</select>
as you can see it still does what you expect but you are not hiding options.
http://jsfiddle.net/upKzW/13/
$('#ExtraField_1').change(function() {
$('#ExtraField_2').val(this.value);
});
http://jsfiddle.net/judearasu/rF8G6/