get a few selected option javascript [duplicate] - javascript

This question already has answers here:
get multiple values from dropdownlist in JavaScript
(3 answers)
Closed 3 years ago.
How do I get the selected value from a dropdown list in case there are more than one selected item using JavaScript? For example:
<select name"nana" id="nana">
<option value="0"</option>
<option value="1"</option>
<option selected="selected" value="2"</option>
<option value="3"</option>
<option selected="selected" value="4"</option>
</select>
I tried:
var e = document.getElementById("nana");
var strUser = e.options[e.selectedIndex].value;
and
document.querySelector("nana").value;
but it returns only the first selected value (2). How can I get all of the selected values?

add multiple="multiple" for multiple for more than 1 select
var selectNana = document.getElementById("nana");
var selectedNana = [];
for (var i = 0; i < selectNana.length; i++) {
if (selectNana.options[i].selected) selectedNana.push(selectNana.options[i].value);
}
console.log(selectedNana);
<select name"nana" id="nana" multiple="multiple" >
<option value="0">0</option>
<option value="1">1</option>
<option selected="selected" value="2">2</option>
<option value="3">3</option>
<option selected="selected" value="4">4</option>
</select>

First make sure your HTML syntax is correct - open tags, like <option, need closing >s too.
Use the query string #nana > option[selected] to select children with the selected attribute, then map to their values:
const selectedValues = Array.from(
document.querySelectorAll('#nana > option[selected]'),
option => option.value
);
console.log(selectedValues);
<select name="nana" id="nana">
<option value="0"></option>
<option value="1"></option>
<option selected="selected" value="2"></option>
<option value="3"></option>
<option selected="selected" value="4"></option>
</select>

Related

Dynamically update a dropdown list based on another dropdown list?

I have a dropdown list with id='apha' with three options and their values are comma separated.
<select class="browser-default" id="alpha">
<option value="a,b,c">One</option>
<option value="d">Two</option>
<option value="e,f">Three</option>
</select>
Another dropdown beta with values. Based on which option is selected in alpha those values should be there in second dropdown beta.
<select class="browser-default" id="beta">
<option value="a">First</option>
<option value="b">Second</option>
<option value="c">Third</option>
<option value="d">Fourth</option>
<option value="e">Fifth</option>
<option value="f">Sixth</option>
</select>
So if One is selected from alpha dropdown. Only values of aplha - a,b,c should be present in beta dropdown - First Second Third
What i have tried:
Without comma separated in values
$('#alpha').on('change', function () {
$('#alpha').html('');
if ($('#alpha').val() == "One") {
$('#alpha').append('<option value="a">First</option>');
$('#alpha').append('<option value="b">Second</option>');
$('#alpha').append('<option value="c">Third</option>');
}
});
You can use split(',') to split values then using for-loop you can get values from split array and finally use $("#beta option[value=" + vals + "]").show() to show options where values matches.
Demo Code:
$("#alpha").on("change", function() {
var values = $(this).val().split(',') //split value which is selected
$("#beta option").hide() //hide all options from slect box
//loop through values
for (var i = 0; i < values.length; i++) {
var vals = values[i]
$("#beta option[value=" + vals + "]").show()//show that option
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<select class="browser-default" id="alpha">
<option value="a,b,c">One</option>
<option value="d">Two</option>
<option value="e,f">Three</option>
</select>
<select class="browser-default" id="beta">
<option selected="selected" value="">--select one-- </option>
<option value="a">First</option>
<option value="b">Second</option>
<option value="c">Third</option>
<option value="d">Fourth</option>
<option value="e">Fifth</option>
<option value="f">Sixth</option>
</select>
Vanilla JS
const beta = document.getElementById('beta');
const betaOpts = [...beta.children];
document.getElementById('alpha').addEventListener(
'change',
(e) => {
beta.innerHTML = betaOpts.filter(
o => e.target.value.includes(o.value)
).map(o => o.outerHTML).join('')
})
<label>Alpha</label>
<select class="browser-default" id="alpha">
<option value="a,b,c">One</option>
<option value="d">Two</option>
<option value="e,f">Three</option>
</select>
<label>Beta</label>
<select class="browser-default" id="beta">
<option value="a">First</option>
<option value="b">Second</option>
<option value="c">Third</option>
<option value="d">Fourth</option>
<option value="e">Fifth</option>
<option value="f">Sixth</option>
</select>

Displaying multiple Select Values into an alert? [duplicate]

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>

Jquery html "select" hide options with value greater than specified [duplicate]

This question already has answers here:
jQuery: Selecting all elements where attribute is greater than a value
(4 answers)
Closed 7 years ago.
I want to be able to hide certain options in html "select", which have value greater that a specific variable:
This is a simple "select" in my html with all options initially available:
<select class="form-control" id="results_per_page">
<option value="4">4</option>
<option value="8">8</option>
<option value="12">12</option>
<option value="16">16</option>
<option value="20">20</option>
<option value="28">28</option>
<option value="40">40</option>
<option value="80">80</option>
<option value="120">120</option>
</select>
Now, my script looks like this:
var itemsFound = "22"; //that's an example -can be any number
// I want to hide the options that are greater than "itemsFound"
$('#results_per_page').find('option[value > "'+itemsFound+'"]').hide();
The line above returns "Uncaught Error: Syntax Error, unrecognized expression: option[value > "22"]
When I use the "equal" though, it works:
$('#results_per_page').find('option[value = "40"]').hide(); //the option with value "40" is indeed hidden
Any ideas of how could this implemented?
You can iterate through each item and check the values:
var itemsFound = "22"; //that's an example -can be any number
itemsFound = parseInt(itemsFound, 10);
//iterate through each option
$('#results_per_page option').each(function() {
//better use parseInt to avoid unexpected bahavour
currentItem = parseInt($(this).attr("value"), 10);
//your condition
if (currentItem > itemsFound) {
$(this).hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="results_per_page">
<option value="4">4</option>
<option value="8">8</option>
<option value="12">12</option>
<option value="16">16</option>
<option value="20">20</option>
<option value="28">28</option>
<option value="40">40</option>
<option value="80">80</option>
<option value="120">120</option>
</select>

Select has an empty value

I`ve a "select":
<select class="date-select2" name="date">
<option selected="selected" value="">All</option>
<option value="11-2015">11-2015</option>
<option value="10-2015">10-2015</option>
<option value="09-2015">09-2015</option>
<option value="07-2015">07-2015</option>
<option value="06-2015">06-2015</option>
<option value="04-2015">04-2015</option>
<option value="03-2015">03-2015</option>
</select>
When I`m try to get value of select,
document.getElementsByClassName('date-select2')[0].value
it normally returns a value of selected item in Chrome. In FF and Safari sometimes it returns an empty string, when selected a numeric value(not "All").
How to deal with it?
I think this might help you:
HTML
<select class="date-select2" name="date" onchange="myFunction(this.value)">
<option selected="selected" value="">All</option>
<option value="11-2015">11-2015</option>
<option value="10-2015">10-2015</option>
<option value="09-2015">09-2015</option>
<option value="07-2015">07-2015</option>
<option value="06-2015">06-2015</option>
<option value="04-2015">04-2015</option>
<option value="03-2015">03-2015</option>
</select>
JavaScript
function myFunction(curValue) {
alert(curValue);
}
Working : Fiddle
Note: Also remember to put your JavaScript code inside body also right before it ends.
var select = document.querySelector('select.date-select2');
// add onchange handler
select.onchange = function(){
var idx = select.selectedIndex;
var val = select.options[idx].value;
// if All is selected use text of option
if(val=="")
val = select.options[idx].textContent;
};
You can try this way to get selected item:
$(".date-select2 option:selected").text();

How do I parse a dropdownlist returned as a HTML string in Javascript/jQuery?

I get a HTML string like this. I want to get the selected value, which, in this case is AN:
<SELECT id=ddl_Freq name=ddl_Freq><OPTION selected value=AN>Annually</OPTION> <OPTION value=BM>Bi-Monthly</OPTION> <OPTION value=MO>Monthly</OPTION> <OPTION value=OT>One Time</OPTION> <OPTION value=QT>Quarterly</OPTION> <OPTION value=WE>Weekly</OPTION></SELECT>
which when formatted looks like this:
<SELECT id=ddl_Freq name=ddl_Freq>
<OPTION selected value=AN>Annually</OPTION>
<OPTION value=BM>Bi-Monthly</OPTION>
<OPTION value=MO>Monthly</OPTION>
<OPTION value=OT>One Time</OPTION>
<OPTION value=QT>Quarterly</OPTION>
<OPTION value=WE>Weekly</OPTION>
</SELECT>
I tried these two approaches, but I wasn't successful.
Approach 1: JavaScript
DdlHtml = document.createElement('select');
DdlHtml.innerHTML = RawDdlString;
item = DdlHtml.options[DdlHtml.selectedIndex].value;
This fails because the string already contains <SELECT> and </SELECT> tags.
Approach 2: jQuery
DdlHtml2 = $.parseHTML(RawDdlString);
item = DdlHtml2.options[DdlHtml2.selectedIndex].value;
This also didn't work as DdlHtml2.options is undefined.
How do I parse this string which contains HTML for a dropdownlist in either Javascript or jQuery?
Wrap the string in a jQuery selector:
$(function() {
var $select = $("<SELECT id=ddl_Freq name=ddl_Freq><OPTION selected value=AN>Annually</OPTION> <OPTION value=BM>Bi-Monthly</OPTION> <OPTION value=MO>Monthly</OPTION> <OPTION value=OT>One Time</OPTION> <OPTION value=QT>Quarterly</OPTION> <OPTION value=WE>Weekly</OPTION></SELECT");
console.log($select.val());
});
Here is an example fiddle
Using jQuery
$('#ddl_Freq').val()
without jQuery,
<SELECT id=ddl_Freq name=ddl_Freq>
<OPTION selected value=AN>Annually</OPTION>
<OPTION value=BM>Bi-Monthly</OPTION>
<OPTION value=MO>Monthly</OPTION>
<OPTION value=OT>One Time</OPTION>
<OPTION value=QT>Quarterly</OPTION>
<OPTION value=WE>Weekly</OPTION>
</SELECT>
var x = document.getElementById("ddl_Freq");
x.options[x.selectedIndex].value;
Output:
"AN"
link to jsbin snippet:
http://jsbin.com/omuxow/1/edit

Categories