I am attempting to grab the selected values of a multi-select dropdown and convert them into a single string for later manipulation. At the moment I have the following code:
function newComic()
{
var elem = document.querySelector("#genreList").selectedOptions;
var arr = [].slice.call(elem);
var genres = arr.join(', ');
window.alert(genres);
}
<select id="genreList" multiple="multiple" name="addGenre[]" style="width: 150px;font-size: 10pt;">
<option value="Action">Action</option>
<option value="Comedy">Comedy</option>
<option value="Fantasy">Fantasy</option>
<option value="Horror">Horror</option>
<option value="Mystery">Mystery</option>
<option value="Non-Fiction">Non-Fiction</option>
<option value="Period">Period</option>
<option value="Romance">Romance</option>
<option value="Sci-Fi">Sci-Fi</option>
<option value="Thriller">Thriller</option>
</select></p>
<p><input type="button" onclick="newComic()" value="Add Comic" id="btnAddComic" style="font-size: 10pt; width: 150px; height:40px;"></p>
The alert window is currently outputting the following:
[object HTMLOptionElement, object HTMLOptionElement, ...]
where '...' represents any further hypothetical options.
What I need is for 'genres' to output as, for example, 'Action, Romance, Thriller' instead.
Thanks in advance for any help.
When you join the array, it is calling the "toString" of each element. In this case, they are DOM elements and return their type. You can use map first to create a new array of strings containing the value of each option:
http://jsfiddle.net/Lfx6r5sm/
var genres = arr.map(function(el){
return el.value;
}).join(', ');
You could iterate through the selected items like so:
<script type="text/javascript">
function newComic(){
var elem = document.querySelector("#genreList").selectedOptions;
var arr = [];
for(var x=0; x<elem.length; x++){
// for the TEXT value
//arr.push(elem[x].text);
// for the value
arr.push(elem[x].value);
}
var genres = arr.join(', ');
window.alert(genres);
}
</script>
You need to iterate through HTMLCollection like this
<script>
function newComic()
{
var elem = document.querySelector("#genreList").selectedOptions;
console.log(elem);
for (var i = 0; i < elem.length; i++) {
console.log(elem[i].attributes[0].nodeValue); //second console output
}
}
</script>
I think jquery is best suited for this task.
HTML
<select id="genreList" multiple="multiple" name="addGenre[]" style="width: 150px;font-size: 10pt;">
<option value="Action">Action</option>
<option value="Comedy">Comedy</option>
<option value="Fantasy">Fantasy</option>
<option value="Horror">Horror</option>
<option value="Mystery">Mystery</option>
<option value="Non-Fiction">Non-Fiction</option>
<option value="Period">Period</option>
<option value="Romance">Romance</option>
<option value="Sci-Fi">Sci-Fi</option>
<option value="Thriller">Thriller</option>
</select>
<p><input type="button" value="Add Comic" id="btnAddComic" style="font-size: 10pt; width: 150px; height:40px;"></p>
jQuery
$("#btnAddComic").click(function(){
var inz = $( "#genreList option:selected" ).map(function(){
return $(this).text();
}).get().join(',');
alert(inz);
});
SEE THE FIDDLE
http://jsfiddle.net/inzamamtahir/1bm45gu7/2/
Related
I have a dropdown list like this:
<select id="box1">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
How can I get the actual option text rather than the value using JavaScript? I can get the value with something like:
<select id="box1" onChange="myNewFunction(this.selectedIndex);" >
But rather than 7122 I want cat.
Try options
function myNewFunction(sel) {
alert(sel.options[sel.selectedIndex].text);
}
<select id="box1" onChange="myNewFunction(this);">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
Plain JavaScript
var sel = document.getElementById("box1");
var text= sel.options[sel.selectedIndex].text;
jQuery:
$("#box1 option:selected").text();
There are two solutions, as far as I know.
both that just need using vanilla javascript
1 selectedOptions
live demo
const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);
areaSelect.addEventListener(`change`, (e) => {
// log(`e.target`, e.target);
const select = e.target;
const value = select.value;
const desc = select.selectedOptions[0].text;
log(`option desc`, desc);
});
<div class="select-box clearfix">
<label for="area">Area</label>
<select id="area">
<option value="101">A1</option>
<option value="102">B2</option>
<option value="103">C3</option>
</select>
</div>
2 options
live demo
const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);
areaSelect.addEventListener(`change`, (e) => {
// log(`e.target`, e.target);
const select = e.target;
const value = select.value;
const desc = select.options[select.selectedIndex].text;
log(`option desc`, desc);
});
<div class="select-box clearfix">
<label for="area">Area</label>
<select id="area">
<option value="101">A1</option>
<option value="102">B2</option>
<option value="103">C3</option>
</select>
</div>
All these functions and random things, I think it is best to use this, and do it like this:
this.options[this.selectedIndex].text
HTML:
<select id="box1" onChange="myNewFunction(this);">
JavaScript:
function myNewFunction(element) {
var text = element.options[element.selectedIndex].text;
// ...
}
DEMO: http://jsfiddle.net/6dkun/1/
Use -
$.trim($("select").children("option:selected").text()) //cat
Here is the fiddle - http://jsfiddle.net/eEGr3/
To get it on React with Typescript:
const handleSelectChange: React.ChangeEventHandler<HTMLSelectElement> = (event) => {
const { options, selectedIndex } = event.target;
const text = options[selectedIndex].text;
// Do something...
};
Using jquery.
In your event
let selText = $("#box1 option:selected").text();
console.log(selText);
Using vanilla JavaScript
onChange = { e => e.currentTarget.options[e.selectedIndex].text }
will give you exact value if values are inside a loop.
function runCode() {
var value = document.querySelector('#Country').value;
window.alert(document.querySelector(`#Country option[value=${value}]`).innerText);
}
<select name="Country" id="Country">
<option value="IN">India</option>
<option value="GBR">United Kingdom </option>
<option value="USA">United States </option>
<option value="URY">Uruguay </option>
<option value="UZB">Uzbekistan </option>
</select>
<button onclick="runCode()">Run</button>
You'll need to get the innerHTML of the option, and not its value.
Use this.innerHTML instead of this.selectedIndex.
Edit: You'll need to get the option element first and then use innerHTML.
Use this.text instead of this.selectedIndex.
<select class="cS" onChange="fSel2(this.value);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS1" onChange="fSel(options[this.selectedIndex].value);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select><br>
<select id="iS2" onChange="fSel3(options[this.selectedIndex].text);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS3" onChange="fSel3(options[this.selectedIndex].textContent);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS4" onChange="fSel3(options[this.selectedIndex].label);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS4" onChange="fSel3(options[this.selectedIndex].innerHTML);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<script type="text/javascript"> "use strict";
const s=document.querySelector(".cS");
// options[this.selectedIndex].value
let fSel = (sIdx) => console.log(sIdx,
s.options[sIdx].text, s.options[sIdx].textContent, s.options[sIdx].label);
let fSel2= (sIdx) => { // this.value
console.log(sIdx, s.options[sIdx].text,
s.options[sIdx].textContent, s.options[sIdx].label);
}
// options[this.selectedIndex].text
// options[this.selectedIndex].textContent
// options[this.selectedIndex].label
// options[this.selectedIndex].innerHTML
let fSel3= (sIdx) => {
console.log(sIdx);
}
</script> // fSel
But :
<script type="text/javascript"> "use strict";
const x=document.querySelector(".cS"),
o=x.options, i=x.selectedIndex;
console.log(o[i].value,
o[i].text , o[i].textContent , o[i].label , o[i].innerHTML);
</script> // .cS"
And also this :
<select id="iSel" size="3">
<option value="one">Un</option>
<option value="two">Deux</option>
<option value="three">Trois</option>
</select>
<script type="text/javascript"> "use strict";
const i=document.getElementById("iSel");
for(let k=0;k<i.length;k++) {
if(k == i.selectedIndex) console.log("Selected ".repeat(3));
console.log(`${Object.entries(i.options)[k][1].value}`+
` => ` +
`${Object.entries(i.options)[k][1].innerHTML}`);
console.log(Object.values(i.options)[k].value ,
" => ",
Object.values(i.options)[k].innerHTML);
console.log("=".repeat(25));
}
</script>
You can get an array-like object that contains the selected item(s) with the method getSelected() method. like this:
querySelector('#box1').getSelected()
so you can extract the text with the .textContent attribute. like this:
querySelector('#box1').getSelected()[0].textContent
If you have a multiple selection box you can loop through array-like object
I hope it helps you😎👍
var selectionlist=document.getElementById("agents");
td2.innerHTML = selectionlist.children[selectionlist.selectedIndex].innerHTML;
ECMAScript 6+
const select = document.querySelector("#box1");
const { text } = [...select.options].find((option) => option.selected);
Try the below:
myNewFunction = function(id, index) {
var selection = document.getElementById(id);
alert(selection.options[index].innerHTML);
};
See here jsfiddle sample
I am working on an asp.net web application and i have the following code to build a search fields section, which build the URL parameters based on the users' input:-
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function(e) {
var count=1;
var s="";
var inputvalue = $("#journal").val();
var inputvalue2 = $("#keywords").val();
var inputvalue3 = $("#datepub").val();
var inputvalue4 = $("#title").val();
var inputvalue5 = $("#localcurrency").val();
var inputvalue6 = $("#locations").val();
var inputvalue7 = $("#dropdown1").val();
var inputvalue8 = $("#dropdown2").val();
if(inputvalue!=null && inputvalue!="")
{
s = s+ "FilterField"+count+"=Journal&FilterValue"+count+"="+inputvalue+"&";
count++;
}
if(inputvalue2!=null && inputvalue2!="")
{
s = s+ "FilterField"+count+"=KeyWords&FilterValue"+count+"="+inputvalue2+"&";
count++;
}
if(inputvalue3!=null && inputvalue3!="")
{
s = s+ "FilterField"+count+"=datepub&FilterValue"+count+"="+inputvalue3+"&";
count++;
}
if(inputvalue4!=null && inputvalue4!="")
{
s = s+ "FilterField"+count+"=Title&FilterValue"+count+"="+inputvalue4+"&";
count++;
}
if(inputvalue5!=null && inputvalue5!="")
{
s = s+ "FilterField"+count+"=localcurrency&FilterValue"+count+"="+inputvalue5+"&";
count++;
}
if(inputvalue6!=null && inputvalue6!="")
{
s = s+ "FilterField"+count+"=locations&FilterValue"+count+"="+inputvalue6+"&";
count++;
}
if(inputvalue7!=null && inputvalue7!="")
{
s = s+ "FilterField"+count+"=dropdown1&FilterValue"+count+"="+inputvalue7+"&";
count++;
}
if(inputvalue8!=null && inputvalue8!="")
{
s = s+ "FilterField"+count+"=dropdown2&FilterValue"+count+"="+inputvalue8+"&";
count++;
}
window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+s);
});
});
</script>
Journal <input type="text" id="journal">
keywords <input type="text" id="keywords">
<select id="datepub">
<option value=""></option>
<option value="1950">1950</option>
<option value="2010">2010</option>
<option value="2017">2017</option>
<option value="audi">Audi</option>
</select>
title
<select id="title">
<option value=""></option>
<option value="TestDoc">test doc</option>
<option value="t">t</option>
</select>
localcurrency
<select id="localcurrency">
<option value=""></option>
<option value="USD">USD</option>
</select>
locations
<select id="locations">
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
</select>
dropdown1
<select id="dropdown1">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
dropdown2
<select id="dropdown2">
<option value=""></option>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
</select>
<button type="button" id="button">search</button>
Where when the user clicks on the search button, the user will be redirected to the /teamsites/Bib%20Test/Forms/search.aspxpage with the filter parameters inside the url, which will show the related records according to the parameters being passed.
now the filtering is working well.. but the problem i am facing is that after i redirect the user to this page /teamsites/Bib%20Test/Forms/search.aspx the filter fields values (such as the local currency, locations, title, etc..) will cleared out.
so can i using JavaScript to assign the filer fields their original values ? i mean can i extract the fields' values from the URL and assign it to them ? so after the user is being redirected to the /teamsites/Bib%20Test/Forms/search.aspx they can still see the filtering fields populated with the filtering values they have entered?
You can accomplish this by doing the following:
Parse the current page's query string to separate out its query parameters
Process those to match up filter field names with their values
Use $('#' + fieldName).val(value) to set the field values in the page
Below, as a demonstration, I'm passing in a hardcoded query string '?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b' into the populateSearchFields() function. In practice, you would use the three functions here, unmodified, but instead of that hardcoded value, pass in window.location.search.
// input: '?a=b&b=c&e=f'
// output: { a: 'b', b: 'c', e: 'f' }
function buildParameterMap(queryString) {
// ignore the ? at the beginning and split the query string into
// pieces separated by &
var pairs = queryString.replace(/^\?/, '').split('&');
var map = {};
pairs.forEach(function(pair) {
// further split each piece to the left and right of the =
// ignore pairs that are empty strings
if (pair) {
var sides = pair.split('=');
map[sides[0]] = decodeURIComponent(sides[1]);
}
});
return map;
}
// input: { FilterField0: 'Name', FilterValue0: 'Fred',
// FilterField1: 'age', FilterValue1: '30' }
// output: { name: 'Fred', age: '30' }
function buildFilterFieldMap(parameterMap) {
var maxFieldCount = 15;
var map = {};
for (var i = 0; i < maxFieldCount; i += 1) {
var filterFieldName = parameterMap['FilterField' + i];
if (filterFieldName) {
map[filterFieldName.toLowerCase()] = parameterMap['FilterValue' + i];
}
}
return map;
}
function populateSearchFields(queryString) {
// build a map from URL query string parameter -> value
var parameterMap = buildParameterMap(queryString);
// build a map from search field name -> value
var filterFieldMap = buildFilterFieldMap(parameterMap);
Object.keys(filterFieldMap).forEach(function(field) {
$('#' + field).val(filterFieldMap[field]);
});
}
populateSearchFields('?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Journal <input type="text" id="journal"> keywords <input type="text" id="keywords">
<select id="datepub">
<option value=""></option>
<option value="1950">1950</option>
<option value="2010">2010</option>
<option value="2017">2017</option>
<option value="audi">Audi</option>
</select> title
<select id="title">
<option value=""></option>
<option value="TestDoc">test doc</option>
<option value="t">t</option>
</select> localcurrency
<select id="localcurrency">
<option value=""></option>
<option value="USD">USD</option>
</select> locations
<select id="locations">
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
</select> dropdown1
<select id="dropdown1">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
</select> dropdown2
<select id="dropdown2">
<option value=""></option>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
</select>
<button type="button" id="button">search</button>
You want to send get request from one page to another. Do something like this:
Part I: send search request in the query string.
$(document).ready(function(){
$('#button').click(function(e) {
var count=1; //out of use
var s = []; //""; //empty array, not empty string
var inputvalue = $("#journal").val();
var inputvalue2 = $("#keywords").val();
var inputvalue3 = $("#datepub").val();
var inputvalue4 = $("#title").val();
var inputvalue5 = $("#localcurrency").val();
var inputvalue6 = $("#locations").val();
var inputvalue7 = $("#dropdown1").val();
var inputvalue8 = $("#dropdown2").val();
if(inputvalue) // !=null && inputvalue!="") //it is redundant. null and empty string are **falsey**
{
s.push('journal='+inputvalue);
//or if you wish to keep your existing format (not recommended because it would produce problems on the search page)
//s.push("FilterField"+count+"=Journal&FilterValue"+count+"="+inputvalue);
//count++;
}
if(inputvalue2) //!=null && inputvalue2!="")
{
s.push('keywords='+inputvalue2);
//for existing format see previous comment
//s = s+ "FilterField"+count+"=KeyWords&FilterValue"+count+"="+inputvalue2+"&";
//count++;
}
/*
//same for other vars
if(inputvalue3!=null && inputvalue3!="")
{
s = s+ "FilterField"+count+"=datepub&FilterValue"+count+"="+inputvalue3+"&";
count++;
}
if(inputvalue4!=null && inputvalue4!="")
{
s = s+ "FilterField"+count+"=Title&FilterValue"+count+"="+inputvalue4+"&";
count++;
}
if(inputvalue5!=null && inputvalue5!="")
{
s = s+ "FilterField"+count+"=localcurrency&FilterValue"+count+"="+inputvalue5+"&";
count++;
}
if(inputvalue6!=null && inputvalue6!="")
{
s = s+ "FilterField"+count+"=locations&FilterValue"+count+"="+inputvalue6+"&";
count++;
}
if(inputvalue7!=null && inputvalue7!="")
{
s = s+ "FilterField"+count+"=dropdown1&FilterValue"+count+"="+inputvalue7+"&";
count++;
}
if(inputvalue8!=null && inputvalue8!="")
{
s = s+ "FilterField"+count+"=dropdown2&FilterValue"+count+"="+inputvalue8+"&";
count++;
}
*/
window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+s.join('&')); //Use the array here
});
});
Part II: Restore values in the search fields.
$(document).ready(function(){
var query = window.location.search.slice(1); //get ?.... less **?**
var terms = query.split('&'); //get pairs like key=value
for(var i = 0, term; term = terms[i]; ++i){ //loop the search terms
var detail = term.split('='); //journal=some
$('#'+detail[0]).val(detail[1]); //set the value provided fields have the same **id**s
}
});
Update based on comments
It is all about ASP.NET. .aspx page prepends server control IDs with parent IDs like parId$controlId. To avoid it and make the client script work set ClientIDMode="Static" attribute to the controls in search.aspx.
<asp:TextBox ID="keywords" runat="server" ClientIDMode="Static"></asp:TextBox>
Update 2
The OP is about ASP.NET. Generally speaking the result can be achieved without any client-side code.
Part I
<form method="GET" action="/search.aspx">
<input type="text" name="keywords" />
<select name="localcurrency">
<option value="USD">US Dollar</option>
<option value="EUR">Euro</option>
</select>
<!--other fields -->
<input type="submit" value="Search" />
</form>
Part II
<%-- search.aspx --%>
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["keywords"] != null)
this.keywords.Text = Request.QueryString["keywords"];
if (!string.IsNullOrEmpty(Request.QueryString["localcurrency"]))
localcurrency.SelectedValue = Request.QueryString["localcurrency"];
//other request query strings
// DoSearch();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="keywords" runat="server"></asp:TextBox>
<asp:DropDownList runat="server" ID="localcurrency">
<asp:ListItem Value="USD">US Dollar</asp:ListItem>
<asp:ListItem Value="EUR">Euro</asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>
Use this if you are not concerned about Internet Explorer or Edge.
When your page has loaded, you can read the search params with the help of URL API. Below is the code to get you started.
Note that this solution depends on being the form param's ID to be equal to the lower cased search param's name.
$(document).ready(() => {
// Change the value to window.location.href for working with browser's URL instead
const href = "http://yourhost.com?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b";
// Initializes the URL object with current location
const url = new URL(href);
// This array will contain all the FilterFields
const keys = [];
for (let entry of url.searchParams) {
if (entry[0].startsWith("FilterField")) {
keys.push(entry[0]);
}
}
keys.forEach(field => {
// Extract the index of FilterField
const idx = field[field.length - 1];
// Get the value of FilterField (this gives us the ID of the form field)
const formField = url.searchParams.get(field).toLowerCase();
// Set the value of form field using .val()
$("#" + formField).val(url.searchParams.get('FilterValue' + idx));
});
// Rest of the code here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Journal <input type="text" id="journal"> keywords <input type="text" id="keywords">
<select id="datepub">
<option value=""></option>
<option value="1950">1950</option>
<option value="2010">2010</option>
<option value="2017">2017</option>
<option value="audi">Audi</option>
</select> title
<select id="title">
<option value=""></option>
<option value="TestDoc">test doc</option>
<option value="t">t</option>
</select> localcurrency
<select id="localcurrency">
<option value=""></option>
<option value="USD">USD</option>
</select> locations
<select id="locations">
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
</select> dropdown1
<select id="dropdown1">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
</select> dropdown2
<select id="dropdown2">
<option value=""></option>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
</select>
<button type="button" id="button">search</button>
I have a dropdown menu with products similiar like this
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananes</option>
<option value="3" >Apples</option>
</select>
I need to remove options by its value. How to do that ?
Pure JavaScript please.
EDIT : I know that I need to use element.removeChild(child) method. But how to reference child by its value. Thats my point.
EDIT 2 : I use the script of zdrohn below and it works. Because I have several fruits dropdowns with the same collection I need to iterate trough all dropdowns and delete it from all dropdowns. This is my code now :
<script type='text/javascript'>
var id = 3;
var el= document.getElementsByClassName("fruits");
for (i=0;i<el.length;i++) {
for(var n = 0; n < el[i].length; n++) {
if(el[i][n].value == id) {
el[i][n].remove();
}
}
</script>
Though it works I wonder about that I do not need to use the parent.removeChild() method. How comes ?
P.S. I wonder that peole vote this question down. As the response shows their are several solutions. Though not all are sufficiantly explained.
Here is a snippet to play with.
The code removes the option with value = 3
window.onload = function() {
var optionToDelete = document.querySelector("select.fruits > option[value='3']");
optionToDelete.parentNode.removeChild(optionToDelete);
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
EDIT: Based on the updated question - I have several fruits drop-downs.
We could make use of querySelectorAll to select all matching elements and forEach to apply the desired logic on each element in the selected list.
window.onload = function() {
var optionsToDelete = document.querySelectorAll("select.fruits > option[value='3']");
optionsToDelete.forEach(function(element, index, array) {
element.parentNode.removeChild(element);
});
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
<select class="fruits">
<option value="1">Seville oranges</option>
<option value="2">Burro Bananes</option>
<option value="3">Baldwin Apples</option>
</select>
<select class="fruits">
<option value="1">Bergamot oranges</option>
<option value="2">Red Bananes</option>
<option value="3">Gravenstein Apples</option>
</select>
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananas</option>
<option value="3" >Apples</option>
</select>
<script type='text/javascript'>
var valueToRemove = 1;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
</script>
Edit:
<select class="fruits" >
<option value="1">Oranges</option>
<option value="2">Bananas</option>
<option value="3">Apples</option>
</select>
<br>
<label>Input value to delete</label><input type='text' id='delete_value'>
<button onclick='remove(document.getElementById("delete_value").value)'>Delete</button>
<script type='text/javascript'>
function remove(item) {
var valueToRemove = item;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
}
</script>
You can select the desired option by using document.querySelector() and a selector of this form
A more complete list of selectors can be found here
Example
var element = document.evaluate( '//option[#value="1"]' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
element.parentNode.removeChild(element)
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>
I would like to select all drop down to be the same as the value selected from the primary dropdown. I got it to work if there is one select selected from the primary dropdown, but will not work if there are two selects, I have added some code below for your information.
HTML:
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select Name</option>
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
</select>
<select id="Qualifications" name="Qualifications">
<option value="select">select</option>
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
</select>
<select id="Qualifications" name="Qualifications">
<option value="select">select</option>
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
</select>
JavaScript:
function setDropDown() {
var index_name=document.QualificationForm.ForceSelection.selectedIndex;
document.QualificationForm.Qualifications.selectedIndex=index_name;
}
Try this
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;
}
You could possibly use the following, though currently untested:
function setDropDown(el){
if (!el) {
return false;
}
else {
var index = el.selectedIndex,
selects = document.getElementsByName('qualifications');
for (var i=0, len=selects.length; i<len; i++){
selects[i].selectedIndex = index;
}
}
}
This requires that you pass the #ForceSelection select element into the function, and so is called like:
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown(this);">
<!-- other stuff -->
</select>
The selectedIndex of this passed-in element will be applied to the other select elements with the name of qualifications.
Also, please allow me to reiterate: an id must be unique within the document in order to be valid HTML.