Javascript - added Orange once in fruitslist drop down list - javascript

<html>
<head>
<script>
function addfruits()
{
for(i = 0; i < document.getElementById("fruits").options.length; i++)
{
if(document.getElementById("fruits").options[i].selected)
{
var fruitslist = document.getElementById("fruitslist");
var option = document.createElement("option");
option.text = document.getElementById("fruits").options[i].text;
fruitslist.add(option);
}
}
}
</script>
</head>
<body>
<select id="fruits" name="fruits[]" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pear">Pear</option>
<option value="grape">Grape</option>
</select>
<input type="submit" name="submit" value=">>" onclick="addfruits()" />
<select id="fruitslist" name="fruitslist[]" style="width: 70px;" multiple>
</select>
</body>
</html>
From above code, first I select Orange from drop down list and click >> button, the Orange value will added in fruitslist drop down list. After that. I select Orange again from drop down list and click >> button, the Orange value will added again in fruitslist drop down list. However, I just want the Orange value added in fruitslist drop down list once. How should I modify it? Can someone help me?

Here is the fix.
<html>
<head>
<script>
function addfruits()
{
for(i = 0; i < document.getElementById("fruits").options.length; i++)
{
if(document.getElementById("fruits").options[i].selected && !isAddedAlready(document.getElementById("fruits").options[i].text))
{
var fruitslist = document.getElementById("fruitslist");
var option = document.createElement("option");
option.text = document.getElementById("fruits").options[i].text;
fruitslist.add(option);
}
}
}
function isAddedAlready(text) {
var fruitslist = document.getElementById("fruitslist");
if(fruitslist.length ==0) return false;
for(var i=0; i<fruitslist.length; i++) {
if(fruitslist.options[i].text === text) return true;
}
return false;
}
</script>
</head>
<body>
<select id="fruits" name="fruits[]" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pear">Pear</option>
<option value="grape">Grape</option>
</select>
<input type="submit" name="submit" value=">>" onclick="addfruits()" />
<select id="fruitslist" name="fruitslist[]" style="width: 70px;" multiple>
</select>
</body>
</html>

Try changing your addFruits function to the following:
function addfruits()
{
for (var i = 0; i < document.getElementById("fruits").options.length; i++)
{
if (document.getElementById("fruits").options[i].selected)
{
var optionText = document.getElementById("fruits").options[i].text;
var fruitslist = document.getElementById("fruitslist");
var found = false;
//Does the item clicked on already exist in the destination list?
for (var j = 0; j < fruitslist.length; j++) {
if (fruitslist[j].text == optionText) {
found = true;
break;
}
}
//If the item does not exist, add it to the list.
if (!found) {
var option = document.createElement("option");
option.text = optionText;
fruitslist.add(option);
}
}
}
}
The important thing to do here is first check that the fruitslist does not contain the item that was clicked on, hence that additional for-loop.

Related

How to enable button upon dropdown item selection in js?

This snippet displays two select elements, and a submit button. Initially, button is disabled.
Desired behavior: enable submit button when both elements have second option (complete) selected. If either one of the elements has first option (received) selected, disable the button.
Current behavior: button is enabled/disabled regardless of the first select element. Meaning: If I select option received in the first dropdown, and option complete in the second, button will be enabled, instead of disabled.
function enableButton() {
var all_statuses = document.body.querySelectorAll(".selected > .form-control");
var option_two = "complete";
for (var i = 0; i < all_statuses.length; i++) {
console.log(i + " This will work")
if (all_statuses[i].value == option_two) {
document.getElementById("btn_completed").disabled = false;
} else document.getElementById("btn_completed").disabled = true;
}
}
$(document).ready(enableButton);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="selected">
<select class="form-control" id="select_one" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
<select class="form-control" id="select_two" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
</div>
</form>
<button id="btn_completed">Completed</button>
So, the question is: How to enable the button if all select elements have option complete selected, or how to disable the button if at least one select element has option different than complete selected?
working code:
<!DOCTYPE html>
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="selected">
<select class="form-control" id="select_one" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
<select class="form-control" id="select_two" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
</div>
</form>
<button id="btn_completed" disabled>Completed</button>
</body>
<script>
function enableButton() {
debugger;
var all_statuses = document.body.querySelectorAll(".selected > .form-control");
var option_two = "complete";
var isdisabled = false;
for (var i = 0; i < all_statuses.length; i++) {
console.log(i + " This will work")
if (all_statuses[i].value != option_two) {
isdisabled = true;
break;
}
}
if(isdisabled) {
document.getElementById("btn_completed").disabled = true;
}
else {
document.getElementById("btn_completed").disabled = false;
}
}
$(document).ready(enableButton);
</script>
</html>

How to get value from select box in html table

I'm trying to retrieve a value from a select box in my HTML table. How can I select the selected value?
What I've tried so far:
this.cells[14].innerHTML;
this.cells[14].children[0].innerhtml;
this.cells[14].children[0].innerText;
The last one .innerText returns all the items in my select box......
var table2 = document.getElementById('table_items_program');
for (var i2 = 1; i2 < table2.rows.length; i2++) {
table2.rows[i2].onclick = function () {
document.getElementById("id").value = this.cells[0].innerHTML;
document.getElementById("select").value = this.cells[14].children[0].innerText;
}
}
<td><select class="selectpicker" multiple>
<?php while ($row9 = mysqli_fetch_assoc($result9)):; ?>
<option value="<?php echo $row9['id']; ?>"><?php echo $row9['id'];?>
</option>
<?php endwhile; ?>
</select></td>
<input style="display: inline" id="id" name="id">
<input style="display: inline" id="select" name="select">
The selected value from my selection box in my HTML table
How can I select the selected value?
You can get the selected index with the method HTMLSelect​Element​.selected​Index
But if I understand your trouble. You try to get the current values of your select. So you need to get the value of your selected options.
You can do it like:
document.getElementById('mySelect').onchange = function() {
let options = this && this.options;
let selectedValues = []
for (var i = options.length; i--;) {
let opt = options[i];
if (opt.selected) {
selectedValues.push(opt.value || opt.text);
}
}
console.log(selectedValues)
}
<select id="mySelect" multiple>
<option value="a"> a </option>
<option value="b"> b </option>
<option value="c"> c </option>
</select>
Implementation into your code example
for (var i2 = 1; i2 < table2.rows.length; i2++) {
table2.rows[i2].onclick = function() {
document.getElementById("id").value = this.cells[0].innerHTML;
var options = this && this.cells[14].children[0].options;
var selectedValues = []
for (var i = options.length; i--;) {
var opt = options[i];
if (opt.selected) {
selectedValues.push(opt.value || opt.text);
}
}
document.getElementById("select").value = JSON.stringify(selectedValues);
}
}
so simple...
ShowSelected.onclick = function()
{
console.clear()
document.querySelectorAll('.selectpicker option:checked').forEach(opt=>console.log(opt.value))
}
.selectpicker {
vertical-align: text-top;
}
choose one or more :
<select class="selectpicker" multiple size=6 >
<option value="a"> A element</option>
<option value="b"> B element</option>
<option value="c"> C element</option>
<option value="d"> D element</option>
<option value="e"> E element</option>
<option value="f"> F element</option>
</select>
<button id="ShowSelected"> Show Selected</button>
Welcome to Stack Overflow!
So, your <select> has the class selectpicker. We can use this to select your <select>!
Try the following to get your value:
document.querySelector(".selectpicker").value;
Or, if you have multiple <select>'s, you can use
[...document.querySelectorAll(".selectpicker")].forEach(opt => {
console.log(opt.value)
});
Hope that clears things up a little.

Disable option when clicked in select

How do I make disable an option when a select is clicked? Here is my code, which does not work. There are no errors in the console.
Here it is:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var numSelect = document.getElementsByClassName("numSelector");
for (var i = 0; i < numSelect.length; i++) {
numSelect[i].innerHTML="<span class='firstSelector'><option>Select Number</option></span><option>1/2</option>";
numSelect[i].onclick = disableSelect;
}
}
function disableSelect() {
for (var a = 0; a < document.getElementsByClassName("firstSelector").length; a++) {
document.getElementsByClassName("firstSelector")[i].innerHTML="<optgroup>Select Number</optgroup>";
}
}
</script>
</head>
<body>
<select class="numSelector"></select>
<select class="numSelector"></select>
</body>
</html>
I'm not sure what you want but here is the ways to disabled dropdown value.
<select id="select1" onclick="disableSelectedItem(this);">
<option>Select Number</option>
<option>1</option>
<option>2</option>
</select>
<select id="select2" onclick="disableFirstItemOnly(this);">
<option>Select Number</option>
<option>1</option>
<option>2</option>
</select>
<script type="text/javascript">
function disableSelectedItem(ddl) {
var value = ddl.options[ddl.selectedIndex].value;
var count = ddl.length;
for (var i = 0; i < count; i++) {
if (ddl.options[i].value == value)
ddl.options[i].disabled = true;
else
ddl.options[i].disabled = false;
}
}
function disableFirstItemOnly(ddl) {
ddl.options[0].disabled = true;
}
</script>
Just use pure HTML
<select required>
<option value="" selected disabled>Select Number</option>
<option>1</option>
<option>etc..</option>
</select>
You could also add the hidden attribute if you don't want it to show up in the dropdown too (at the moment it is visible but disabled)
The required attribute on the <select> means that not choosing a number will prevent submission (though you should still validate serverside)

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>

Store contents of drop down box into var, then load the new drop down box contents using the var

1.) How can I use javascript to save the contents of box1 and store it into a variable (x), separating them all by commas?
Since I will be doing some database work in the background, it is important that the values are stored using this method.
Example of whats in the drop down box:
[BOX1]
volvo
saab
mercedes
audi
Resulting var:
var x = volvo,saab,mercedes,audi
2.) Using the variable (x) how can I repopulate the drop down [BOX2] with the comma separated values.
[BOX2]
volvo
saab
mercedes
audi
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="box1" style="width: 100px;">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br>
<input type="button" value="Save" name="Save">
<br><br>
<input type="button" value="Populate" name="Populate"><br>
<select id="box2" style="width: 100px;" name="D1"></select>
<br>
</body>
</html>
You could retrieve the options and simply put them into the other selectbox, by adding an event handler.
Working Example
//temp holds DOM elements
//temp2 holds only the values
var temp = [];
var temp2 = [];
function save() {
var cH = document.getElementById('box1').children;
for (var i in cH) {
if(cH.hasOwnProperty(i) && cH[i].nodeName == 'OPTION') {
temp.push(cH[i]);
temp2.push(cH[i].value);
}
}
alert(arr2csv());
}
function populate() {
var popul = csv2arr();
var box2 = document.getElementById('box2');
/*
for(var i=0;i<temp.length; i++) {
box2.options.add(new Option(temp[i].text,temp[i].value));
}
*/
for(var i=0;i<popul.length; i++) {
box2.options.add(new Option(popul[i],popul[i]));
}
}
function arr2csv() {
return temp2.join();
}
function csv2arr() {
return arr2csv().split(',');
}
document.getElementById('testsave').addEventListener("click", save);
document.getElementById('testpopulate').addEventListener("click", populate);

Categories

Resources