Append selected items to a list - javascript

I want to create a dropdown box with a few items. Once the user selects the item and clicks the '+' button, the item is added below to a 'basket' section. They should be able to add multiple items over and over.
document.getElementById("button").onclick = function() {
var a = document.getElementById("selection");
var item = a.options[a.selectedIndex].text;
document.getElementById("basket").innerHTML = item;
var counter = 1;
while (counter <= 1) {
var list = document.write(item);
counter++;
}
}
<h1>Select your items!</h1>
<form id="myForm">
<p>Item:
<select id="selection">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
<button id="button">+</button></p>
</form>
<br><br><br>
<h1>Basket</h1>
<p id="basket"></p>
When the button is pressed, all current content disappears and the item selected appears on its own.

The button in the form has no type="button". Therefore it is used as submit button and that's why you get the blank page.
You don't need a loop.
Example
var button = document.getElementById("button");
var select = document.getElementById("select");
var basket = document.getElementById("basket");
// Add text
function addToBasket() {
var li = document.createElement("li");
li.innerHTML = select.options[select.selectedIndex].text;
basket.appendChild(li);
}
button.addEventListener("click", addToBasket);
<h1>Select your items!</h1>
<form id="myForm">
<p>Item:
<select id="select">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
<button id="button" type="button">+</button></p>
</form>
<h1>Basket</h1>
<ul id="basket"></ul>

You are not concatenating them. document.getElementById("basket").innerHTML = item; removes everything in the basket and add only the selected one.
Use this to concatenate the new item with what already exists in the basket document.getElementById("basket").innerHTML += item;. You can style it to make the basket look nice.

Related

Delete created div js

Tell me please, there is code, when you click on select option, a div is added. Please help me add a delete button next to each created div and delete this div.
var p = document.getElementById("inputi");
var length = 1;
function add_input_from_select(select) {
var new_input = document.createElement("input");
new_input.name = "my_input";
new_input.value = select.value;
var div = document.createElement('div');
div.innerHTML = '<br>div элемент №' + length + '<br>';
div.appendChild(new_input);
p.appendChild(div);
length++;
}
function add_input_old() {
add_input_from_select(document.getElementById("selector"));
}
<select id="selector" onchange="add_input_from_select(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<form>
<div id="inputi"></div>
</form>
Very crudely, you can add a button in the same way you are currently adding an input and a div but bind a click event to the button so that when clicked it deletes it's parent and everything inside it.
var p = document.getElementById("inputi");
var length = 1;
function add_input_from_select(select) {
var new_input = document.createElement("input");
var div = document.createElement('div');
var button_delete = document.createElement('button');
new_input.name = "my_input";
new_input.value = select.value;
button_delete.innerText = "Delete"
button_delete.addEventListener("click", function(){
this.parentNode.remove();
});
div.innerHTML = '<br>div элемент №' + length + '<br>';
div.appendChild(new_input);
div.appendChild(button_delete);
p.appendChild(div);
length++;
}
function add_input_old() {
add_input_from_select(document.getElementById("selector"));
}
<select id="selector" onchange="add_input_from_select(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<form>
<div id="inputi"></div>
</form>
These are the things I have created to achieve your goal
Created a delete button and appended it to the div
Created an onclick event for the delete button and deleted the current div using display:none
var p = document.getElementById("inputi");
var length = 1;
var deleteBtn;
function add_input_from_select(select) {
var new_input = document.createElement("input");
new_input.name = "my_input";
new_input.value = select.value;
var div = document.createElement('div');
deleteBtn = document.createElement('button'); //Adding delete button
deleteBtn.innerHTML = 'Delete';
deleteBtn.setAttribute("type", "button");
div.innerHTML = '<br>div элемент №' + length + '<br>';
div.appendChild(new_input);
div.appendChild(deleteBtn);
deleteBtn.setAttribute("onclick", function() { alert("blabla"); });
p.appendChild(div);
length++;
deleteBtn.onclick = function(){ //Event for deleting the div
div.style.display = "none";
}
}
<select id="selector" onchange="add_input_from_select(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<form>
<div id="inputi"></div>
</form>
Although your question was framed in a way that it was difficult to understand what you want, I think I've got it.
I think it would be MUCH easier if you tried to do this in jQuery. Here's a very simple way to do it (I've added some comments incase you are new to jQuery) -
1 - Create the snippet code that you want to add to the DOM. (You just needed an extra button element in yours).
2 - use jQuery for manipulating DOM based on click and change events.
$(document).ready(function (){
$('#selector').change(function() {
// getting the input tag ready with value from selector
$divToAppend = '<div><input type="text" value="'+$(this).val()+'"><button type="button" id="btn-delete">Remove</button></div>'
// appending the div to the form
$('form').append($divToAppend);
});
// binding a function to EVERY btn-delete ID in the 'form' scope
$('#form').on('click', '#btn-delete', function() {
// this goes to the btn-delete, looks for it's parent, which is the <div> and the removes it from the DOM
$(this).parent().remove();
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selector">
<option selected hidden>Select something!</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<form id="form">
</form>

Show dropdown option in button

I have a drop-down list what i want to do is when i choose an option from this list it displays a button under it with that option, the user can choose more than one option so i want to display many buttons with a close sign so the user can remove that option, how can i do that using JavaScript? here is my code:
$('select').on('change', function() {
var unselected = $('select').filter(function() {
return this;
$('.btn').show();
});
});
.btn{
display:none;}
<div class="form-group">
<label>Pick your item</label>
<select class="form-control">
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
<option>Item 4</option>
</select>
</div>
<button type="button" class="btn btn-default">Chosen value should be here</button>
Like this you haven't the close sign, but it would work almost the same way.
// everytime some option is selected in the select with "cars" id
$('#cars').on('change', function() {
// it will run through the selected options
$('option:selected').each(function() {
var op = $(this);
var text = op.text();
// checks if the button is already there
var already_there = false;
$('#btns button').each(function() {
var btn = $(this);
if(btn.text() == op.text()) {
already_there = true;
// leaves the verification
return false;
}
});
// if it isn't, appends to the div with id "btns"
if(!already_there) {
var btn = $('<button type="button" class="btn btn-default" onclick="removeBtn(this)"></button>');
btn.append(text);
$('#btns').append(btn);
}
});
});
// removes a button (obvious xD)
function removeBtn(btn) {
$(btn).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head><title>Test</title></head>
<body>
<select multiple id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<div id="btns"></div>
</body>
</html>

jquery get current selected value from multiple

I have select drop down where I use array sign in name like
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
Now I need to get current (last) selected value from drop down on change event.
What I have tried so far is
var clicked = $('#service_id option:selected').last().val();
alert(clicked);
//also tried as
//$(this).closest('select').find('option').filter(':selected:last').val();
//and this is tried too
// $(this).val();
// this.value;
All these giving me wrong value when multi select.
What I need
If select four then next select one it should alert 1 (remember when multi selection).
If select three and then next select four then it should alert 4
In brief ALWAYS need Clicked option's value even in multi select
** Not possible to remove array sign from name services[]
There is no native way, but you could save the order of the options clicked, then get the last.
ie, against a data attribute on the select:-
$('#service_id option').click(function() {
var values = $(this).parent().data('values') || [];
var index = values.indexOf(this.value);
index >= 0 ? values.splice(index, 1) : values.push(this.value);
$(this).parent().data('values', values);
});
$('#service_id').click(function() {
var values = $(this).data('values');
console.log(values);
var last = values[values.length - 1];
console.log('last:' + last);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
Try this demo
$(function(){
var last_selected;
$("#service_id option").click(function(){
if($(this).is(":selected")) {
last_selected = $(this).attr('value');
}
$("#result").html(last_selected);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
<p>Last selected : <span id="result"></span></p>
So you just want to get the last selected element?
Just create a variable to store the last selected element in each option click as shown by this demo:
var currLast = null;
$('#service_id').children().on('click', function(){
var val = $(this).val();
if (currLast === val) { // do nothing if current selected is the same elem
return;
}
currLast = val;
console.log(currLast)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>

How to get the index of a selected item in listbox and add to listbox two with button?

I am looking to get the index of the selected item in a list box to add the selected item to list box 2.
The listbox was created in HTML.
<div class="clearfix">
<div class="select-container">
<select name="sometext" size="5">
<?
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheets()[1]);
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("A1:A"+lastRow);
var data = myRange.getValues();
?>
<? for (var i = 0; i < data.length; ++i) { ?>
<option><?!= data[i] ?></option>
<? } ?>
</select>
</div>
<div class="buttons">
<div><button onclick='addMonitoredFolder()' id='button1'>Add</button></div>
</div>
So when I press button 'Add', I want the currently selected item in list box 1 to be added to listbox 2. It would be good that if the user selects multiple options in the list then it will add these or at least know how to handle this. I have function addMonitoredFolder in there because I was trying to figure it out by just can't get my head around it.
<div class="select-container">
<select name="sometext" size="5">
<option>option</option>
</select>
</div>
Thanks!
Here is code that can get multiple selections from a list, and transfer the choices to the second list:
index.html
<!DOCTYPE html>
<html>
<body>
<div>List Box One</div>
<select id="slctOne" multiple>
<option value="one">Value One</option>
<option value="two">Value Two</option>
<option value="three">Value Three</option>
<option value="four">Value Four</option>
</select>
<div>List Box Two</div>
<select id="slctTwo" multiple>
<option value="one">Value One</option>
<option value="two">Value Two</option>
<option value="three">Value Three</option>
<option value="four">Value Four</option>
</select>
<button onmouseup="getAndTransfer()">Get Choices</button>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>
</body>
</html>
JavaScript.html
<script>
window.getAndTransfer = function() {
var allChoices = getMultiple();
putChoicesIntoSelectTwo(allChoices);
};
window.getMultiple = function() {
//console.log('getMultiple ran')
var allOptionNodesSelected = document.getElementById('slctOne').querySelectorAll('option:checked');
var howManySelected = allOptionNodesSelected.length;
console.log('number of option nodes: ' + howManySelected);
var optionElmt1 = allOptionNodesSelected[0];
console.log('optionElmt1.selected: ' + optionElmt1.selected);
var i=0,
arryAllOptions = [];
for(i=0;i<howManySelected;i+=1) {
console.log('optionElmt1.selected: ' + allOptionNodesSelected[i].value);
arryAllOptions.push(allOptionNodesSelected[i].value);
};
return arryAllOptions;
};
window.putChoicesIntoSelectTwo = function(theChoices) {
//Get select list two element
var selectListTwo = document.getElementById('slctTwo');
var allOptions = selectListTwo.getElementsByTagName("option"); //Get all current options inside of this select tag
var i = 0, thisOptionVal="";
//console.log(allOptions.length);
for (i=0;i<allOptions.length;i+=1) {
thisOptionVal = allOptions[i].value;
if (theChoices.indexOf(thisOptionVal) !== -1) {
allOptions[i].selected = true;
} else {
allOptions[i].selected = false;
};
};
};
</script>

Open the html selected list with a button click

I have created a option list in a webpage where I want to open the select list with a button created with a <div> when a option selected from the list then the selected value comes on the div also.
So here I want the javascript attribute to open the list on button click something like this
document.getElementById('selectedlist').open.
any body have suggestion about this?
Take a look at http://code.google.com/p/expandselect/. I think this is what you want.
Then you can open the select like this.
ExpandSelect("myselect_id")
Here is the simple Javascript code to open(toggle) the select box on clicking the button.
<script type="text/javascript">
function expandSelect(id){
var select_flag = document.getElementById('select_flag').value;
if(select_flag==1){
var select_box = document.getElementById(id);
select_box.size = 1;
document.getElementById('select_flag').value = 0;
}else{
var select_box = document.getElementById(id);
select_box.size = select_box.options.length;
document.getElementById('select_flag').value = 1;
}
}
</script>
<button onclick="expandSelect('select_box')"> Toggle Select Box </button>
<div id="container">
<select name="select_box" id="select_box" >
<option value="">Select</option>
<option value="">option1</option>
<option value="">option2</option>
<option value="">option3</option>
<option value="">option4</option>
<option value="">option5</option>
<option value="">option6</option>
</select>
<input type="hidden" name="select_flag" id="select_flag" value="0">
</div>

Categories

Resources