Display selected items in a list - javascript

How to display selected items in a list?
So that the elements selected in the selector are displayed in the list below it.
Example code:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="md-form">
<select name="users" multiple="multiple"
required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</body>
</html>
What should be the result:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<select name="users" multiple="multiple"
required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Selected items:
<ul>
<li>1</li>
<li>3</li>
</ul>
</body>
</html>

You need check your selected is exist or not and create it.
if( document.getElementById("mySelect") != undefined) {
document.getElementById("mySelect").remove();
}
var selectList = document.createElement("select");
And you map function to create options selected in change event handle as
function change (options) {
var parent = document.getElementsByClassName("md-form")[0];
if( document.getElementById("mySelect") != undefined) document.getElementById("mySelect").remove();
var selectList = document.createElement("select");
let selected = [...options].filter(o => o.selected).map(o => {
selectList.id = "mySelect";
selectList.multiple = "multiple";
parent.appendChild(selectList);
var option = document.createElement("option");
option.value = o.value;
option.text = o.text;
selectList.appendChild(option);
});
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="md-form">
<select name="users" multiple="multiple"
required onchange="change(this.options);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</body>
</html>

Another approach is to do something like that (added notes inside the code):
const userSelection = document.querySelector('[name="users"]'); // select element
const userSelect = document.querySelector('ul'); // list container
userSelection.addEventListener('change', function() { // add event listener to change of the select
const options = userSelection.querySelectorAll('option'); // list of options
options.forEach(option => { // iterate them
if(option.selected == true) { // if one of them selected
const newLI = document.createElement('li'); // create li element
newLI.textContent = option.value; // add the value of selected option as text content
newLI.addEventListener('click', function() { userSelect.removeChild(this); }); // BONUS: remove list item with click
userSelect.appendChild(newLI); // append the new created li element to the list
}
});
});
<div class="md-form">
<select name="users" multiple="multiple" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<ul></ul>
Hope that helps!

I was thinking that you could use JavaScript (JS) as a way to get the items that are selected and paste them elsewhere (wherever you want).
Try this:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<select id="select" name="users" multiple="multiple"
required>
<option class="option" value="1">1</option>
<option class="option" value="2">2</option>
<option class="option" value="3">3</option>
</select>
Selected items:
<ul>
<li>1</li>
<li>3</li>
</ul>
</body>
</html>
Then add JS:
// Get the select input
document.getElementByID("select")
// Get the options
document.getElementByClassName("option")
// Get the options that are selected
var print = `.option:[active]`;
// Print (paste) the selected options elsewhere on the page
if print {
document.write(print);
}
Please tell me if this works, as it might not. After all, I'm just an 8-year old, and just starting to learning web development.

You could use the following:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="md-form">
<select name="users" multiple="multiple"
required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<script>
// References to elements
var select = document.querySelector('select'),
options = Array.from(select.querySelectorAll('option')),
form = document.querySelector('.md-form'),
ul = document.createElement('ul');
// Variables with information
var selected = [];
select.addEventListener('change', function() {
selected = [];
ul.innerHTML = '';
options.map(function(el) {
if (el.selected) selected.push(el);
});
if (selected.length) {
selected.map(function(el) {
var li = document.createElement('li');
li.textContent = el.textContent;
ul.appendChild(li);
});
form.appendChild(ul);
} else {
form.removeChild(ul);
}
});
</script>
</body>
</html>
Working fiddle:
https://jsfiddle.net/1j7a9h35/

Related

get the selected value of the select box

I have the selectbox and that selected box has one value selected, now i can change the value and i want that it should pick the changed value instead of the already selected value
i am using it like this
var x= document.getElementById("numbervalue");
var y= document.getElementById("dayvalue");
ax = dnum.options[x.selectedIndex].value;
at = dDay.options[y.selectedIndex].value;
ut the above only giving me the previously selected value instead of new one
Hopefully this helps
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>get value of select box</title>
<style>
body {
font-family: Courier, monospace;
}
#output {
margin-top:10px;
text-align:center;
padding:10px;
width: 200px;
height:100px;
border-style:groove;
}
.info {
font-size: 12px;
width: 270px;}
</style>
</head>
<body>
<h3>select box stack overflow</h3>
<p class = "info">On any change in an option element, the JS will use the vals from the numbervalue option element to reset the val in the dayvalue option element.<br><br>You must change the number to change anything</p>
<label for = "dayvalue">Choose a day:</label>
<select name="dayvalue" id="dayVal" onchange="readBoxes()">
<option value="m">Monday</option>
<option value="t">Tuesday</option>
<option value="w">Wednesday</option>
<option value="th">Thursday</option>
<option value="f">Friday</option>
<option value="sat">Saturday</option>
<option value="sun">Sunday</option>
</select>
<br>
<label for = "numbervalue">Choose a number:</label>
<select name="numbervalue" id="numVal" onchange="readBoxes()">
<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>
<option value="7">7</option>
</select>
<div id="output">Day of Week</div>
<p>-h34dsp1nns</p>
<script>
function readBoxes() {
var out = document.getElementById("output");
var day = document.getElementById("dayVal");
var num = document.getElementById("numVal");
var numIndex = num.selectedIndex;
day.selectedIndex = numIndex; //resets the index
var dayVal = day[numIndex]; //gets the option element at an index
out.innerHTML = dayVal.text;
}
</script>
</body>
</html>

How to get latest value selected from multiselect dropdown

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>

How can I build multiple step selectors in HTML page?

I have a problem with HTML contact form.
For example I have that schema with element dependencies:
Where are many selectors and inputs depends on what is selected in previous steps.
How can I build that logic in HTML and Javascript (Jquery)?
For result I need to return one input hidden field, where are placed all selected values, for example:
Cash - at Compensa partners - Outside Riga - Serviss from selected option
Maybe there are some Jquery solutions for that purpose?
P.S. I can only use HTML pages
Minimal example: write out all the different selects and only show the relevant one. You can add all the other dependencies in a similar way. Building the selects dynamically will be less, but more complicated code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example</title>
<style>
.hide {
display: none;
}
.show {
display: block;
}
</style>
</head>
<body>
<div id="claim">
<select>
<option value="default" disabled="disabled" selected="selected">Select a claim type</option>
<option value="cash">Cash</option>
<option value="repair">Repair</option>
<option value="glazing">Glazing</option>
</select>
</div>
<div id="cash" class="hide">
<select>
<option value="partners">At Compensa partners</option>
<option value="office">Compensa Office</option>
<option value="broken">Verhicle is broken</option>
</select>
</div>
<div id="repair" class="hide">
<select>
<option value="age">Car age</option>
<option value="place">Serviss place</option>
</select>
</div>
<script>
var dependencies = {
'claim' : {
'cash' : 'nextDep',
'repair' : 'nextDep',
'glazing' : 'nextDep'
}
};
document.querySelector('#claim select').addEventListener('change', function ( event ) {
var parentID = event.target.parentNode.id,
value = event.target.value;
Object.keys(dependencies[parentID]).forEach(function ( key ) {
var select = document.querySelector('#' + key),
currentClass = select.className;
if (select.id === value && currentClass === 'hide') select.className = 'show';
else if (currentClass !== 'hide') select.className = 'hide';
});
});
</script>
</body>
</html>

Get text from select tag in html

I have two dropdown menus named date and time respectively. I want to get the
text from the option tag when I click a button, but the javascript function does not seem to work. I 've found similar questions (and answers) about this but nothing worked. The code is below:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function collectData() {
var index = document.getElementById("date").selectedIndex;
var date = document.getElementById("date").options[index].text;
window.alert("You selected: " + date);
}
</script>
</head>
<body>
<select name="date">
<option value="1">date 1</option>
.....
</select>
<select name="time">
<option value="1">time 1</option>
.....
</select>
<button type="button" onclick="collectData()">Get data</button>
</body>
</html>
You're selecting the element by id but you didn't assign the id anywhere.
You need to add the correct id to the item:
<select id="date" name="date">
....
<select id="time" name="time">
Or you could select the items by name:
var index = document.getElementsByName("date")[0].selectedIndex;
Note: getElementsByName returns an array, thats why the [0] was added to select the first item that has that name.
Change code to
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function collectData() {
var e = document.getElementById("date");
var strUser = e.options[e.selectedIndex].value;
window.alert("You selected: " + strUser);
}
</script>
</head>
<body>
<select name="date" id="date">
<option value="1">date 1</option>
..
</select>
<select name="time">
..
</select>
<button type="button" onclick="collectData()">Get data</button>
</body>
</html>
Try this:
function collectData() {
var ddl = document.getElementById("dateSelect");
var text = ddl.options[ddl.selectedIndex].text;
window.alert("You selected: " + text);
}
<select id="dateSelect" name="date">
<option value="1">date 1</option>
<option value="2">date 2</option>
<option value="3">date 3</option>
</select>
<button type="button" onclick="collectData()">Get data</button>
Here a CodePen
you are using getElementById('date').so add id attribute to select element.

how change the value on change select tag

How can I change the values in the second select on change of the first one?
When I change to Cool drink then show Pepsi, Coac & Sprite only. When I change to Food then show Pizza, Chicken & Bar b Q
<select id="food">
<option>Cool Drink</option>
<option>Food</option>
</select>
<select id="Person">
<option>Pepsi</option>
<option>Coac</option>
<option>Sprite</option>
<option>Bar b Q</option>
<option>Chicken</option>
<option>Pizza</option>
</select>
This can be by using ajax.
<html>
<head>
<title>Food Order</title>
</head>
<body>
<select id="food" >
<option value="1">Cool Drink</option>
<option value="2">Food</option>
</select>
<select id="Person" >
<option>Select Option</option>
</select>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#food").change(function(){
var txt=$("#food").val();
$("#Person").empty();
$.ajax({
url : 'load.php',
method : 'POST',
data : {txt:txt},
success:function(data){
$("#Person").html(data);
}
});
});
});
</script>
</html>
Add another page with the name of (load.php) and add this code
<?php $data=$_POST['txt']; ?>
<?php if ($data == 1): ?>
<option>Pepsi</option>
<option>Coac</option>
<option>Sprite</option>
<?php else: ?>
<option>Bar b Q</option>
<option>Chicken</option>
<option>Pizza</option>
<?php endif ?>
As simple as I could make it. Very weird we cannot use :visible on the options
$('#food').on("change",() => {
const $opts = $('#Person option');
$opts.each((_,el) => $(el).toggleClass("hidden"));
$('#Person').val($opts.not('.hidden').eq(0).val());
})
.hidden {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="food">
<option>Cool Drink</option>
<option>Food</option>
</select>
<select id="Person">
<option value="1">Pepsi</option>
<option value="2">Coca Cola</option>
<option value="3">Sprite</option>
<option value="4" class="hidden">Bar b Q</option>
<option value="5" class="hidden">Chicken</option>
<option value="6" class="hidden">Pizza</option>
</select>
Crate list of drinks and food in JS.
const drinks = ["Pepsi", "Cola"];
const food = ["Pizza 1", "Pizza 2"]
and then create JS function, which will be fired by event onChange and update second dropdown list.
function changeList(name){
if (name === "Food") {
// fill list with foods
}
// fill list with drinks
}
Change the second dropdown contents depending on the data-type attribute of the first select on an onChange event. See below.
$('#food').on('change', function(){
const drink = ["Pepsi", "Coac", "Sprite"];
const food = ["Bar b Q", "Chicken", "Pizza"]
let type = $(this).children(":selected").data('type')
var $dropdown = $("#Person");
if (type=='food') {
arr = food
} else if (type=='drink') {
arr = drink
}
$dropdown.find('option').remove();
for (i = 0; i < arr.length; i++) {
$dropdown.append($("<option />").text(arr[i]));
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<title>Food Order</title>
</head>
<body>
<select id="food" >
<option>Please Select</option>
<option data-type="drink">Cool Drink</option>
<option data-type="food">Food</option>
</select>
<select id="Person" >
<option>Please Select Type</option>
</select>
</body>
</html>

Categories

Resources