JavaScript- Add Selected Option into a list - javascript

So I'm attempting to have a combo box be populated by a option the user selects. Once the user selects the item and clicks Add, I want to add the text value of the selected item into a list.
I have the first part working as I'd like, however, I'm having a rough time with Adding the values into the list. I honestly have no idea how to accomplish it or what would be the best way? If someone could just send me along the right path of what I need to look into and what sort of event listeners, methods, I should look at would be great. I'm super new to JavaScript and I'm having a hard time wrapping my head around it.
What I have so far:
function changeOptions(link) {
if (link=="") {
return; }
switch(link) {
case "Category1":
var inventory=new Array (
"Item1",
"Item2",
"Item3");
break;
case "Category2":
var inventory=new Array (
"Item4",
"Item5",
"Item6");
break;
}
i = document.form.items.options.length;
if (i > 0) {
document.form.items.options.length -= i; document.form.items.options[i] = null;
}
for (i=0; i< inventory.length; i++) {
document.form.items.options[i] = new Option();
document.form.items.options[i].text = inventory[i];
document.form.items.options[i].value = inventory[i];
}
}
<form name=form >
<b>Select a Category</b><br />
<a onclick="changeOptions('Category1')">Category1</a> |
<a onclick="changeOptions('Category2')">Category2</a>
<br /><br/>
<b>Inventory</b><br/>
<select name="items" multiple="multiple" style="height:150px;width:400px;">
<option value="">Select An Item</option>
</select>
<input type="submit" name= "add" value="Add">
</form>

I've added some code to append the selected value to a list beneath your combo box. I added a form event listener for submit. On submit we get the value of the select box and add it to a list. You can tweak this and add validation and stuff. I also added some id's to the html to query the elements with in the JS.
var select = document.getElementById('select');
var form = document.getElementById('form');
var list = document.getElementById('list');
var addItem = function(item) {
return '<li>' + item + '</li>';
}
var handleSubmit = function(e) {
e.preventDefault();
list.innerHTML += addItem(select.value);
}
form.addEventListener('submit', handleSubmit);
function changeOptions(link) {
if (link == "") {
return;
}
switch (link) {
case "Category1":
var inventory = new Array(
"Item1",
"Item2",
"Item3");
break;
case "Category2":
var inventory = new Array(
"Item4",
"Item5",
"Item6");
break;
}
i = document.form.items.options.length;
if (i > 0) {
document.form.items.options.length -= i;
document.form.items.options[i] = null;
}
for (i = 0; i < inventory.length; i++) {
document.form.items.options[i] = new Option();
document.form.items.options[i].text = inventory[i];
document.form.items.options[i].value = inventory[i];
}
}
<form id="form" name=form>
<b>Select a Category</b>
<br />
<a onclick="changeOptions('Category1')">Category1</a> |
<a onclick="changeOptions('Category2')">Category2</a>
<br />
<br/>
<b>Inventory</b>
<br/>
<select id="select" name="items" multiple="multiple" style="height:150px;width:400px;">
<option value="">Select An Item</option>
</select>
<input id="btn" type="submit" name="add" value="Add">
</form>
<ul id="list">
</ul>

Related

Loop through multiple HTML elements with the same ID and build objects with their data

var serviceGroupName = document.querySelectorAll('packageGroupName').value;
var sourceType = document.getElementById("multiple-checkboxes");
if (serviceGroupName !== '')
{
var serviceArray = [];
for (i = 0; i < sourceType.selectedOptions.length; i++)
{
serviceArray.push(parseInt(sourceType.selectedOptions[i].value));
}
var groupName = {};
groupName[serviceGroupName] = serviceArray;
ungroupedServiceArray = [];
}
document.getElementById('addGroup').onclick = duplicate;
var i = 0;
var original = document.getElementById('addService');
function duplicate()
{
var clone = original.cloneNode(true);
clone.id = "addService1" + ++i;
original.parentNode.appendChild(clone);
}
<div id="addService">
<p><b>Service Group Name: </b></p>
<div class="form-group">
<input type="text" class="packageGroupName" id="packageGroupName" minlength= 1 placeholder=" Group Name" >
</div>
<p><b>Add Services</b></p>
<div class="form-group">
<select id="multiple-checkboxes" multiple="multiple" class='packageGroupName'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1"></label>
<button type="button" class="btn btn-primary" onclick="duplicate()" id="addGroup">Add </button>
</div>
</div>
I am trying to loop through an undefined number of HTML elements all with the same id. The reason being, every time the user clicks a button on the form, it creates a new text field and drop down, identical to the original.
I am looking to grab a string value from a text box and multiple values from a multiselect list and associate them where the string value is the key, and the multiple values from the drop down list are the values.
Here is the javascript code I have thus far:
This is grabbing the data from the text field and the multiselect list
var serviceGroupName = document.querySelectorAll('packageGroupName').value;
var sourceType = document.getElementById("multiple-checkboxes");
if (serviceGroupName !== '')
{
var serviceArray = [];
for (i = 0; i < sourceType.selectedOptions.length; i++)
{
serviceArray.push(parseInt(sourceType.selectedOptions[i].value));
}
var groupName = {};
groupName[serviceGroupName] = serviceArray;
ungroupedServiceArray = [];
}
This is how I'd like the final output to look. Basically, however many times the user creates a new textbox and muliselect list it will create this output:
"Textbox value": [
multiselect_values,
multiselect_values,
multiselect_values,
multiselect_values
]
"Textbox value2":[
multiselect_values2,
multiselect_values2,
multiselect_values2
]
As others put it, you need to use a class name instead of using just an id. Instead of <div id="addService">" use <div id="addService" class="service">.
Then in your code you would do something like this:
var servicelist = document.querySelectorAll('.service')
for(var i=0; i<servicelist.length; i++){
var serviceGroupName = servicelist[i].querySelector('input.packageGroupName').value;
var sourceType = document.querySelector("select.packageGroupName");
..... the rest of your code
}

Fill multiselect dropdown depending on select

I have a select dropdown list and a multiselect dropdown. And i want the multiselect one to be depended on the select one. How can i do it?
<div class="row">
<div class="col" ><label>Which class: </label><select name="type_of_subject_c" id="type_of_subject_c" tabindex="1">
<option value="" selected="selected">--не выбрано--</option>
<option value="5">5th </option>
<option value="6">6th</option>
<option value="7">7th</option>
<option value="8">8th</option>
</select>
</div>
And i want, for example, if a person chose 5th - show in the multiselect field such options as "Math", "English", "Literature"
If a person chose 6th - show "Math", "Science", "Music"
etc.
<div class="row">
<div class="col"><label>Coruses: </label><select name="course_subj_c[]" id="course_subj_c" multiple="multiple" tabindex="1" >
<option value="math">Math</option>
<option value="eng>English</option>
<option value="lit">Literature</option>
First of all you should always add code to your question even if it is not working. Stackoverflow is a place to learn, how can we help you if you don't share your work.
Array data contains all your data. We add options to both selects dynamically.
Function init() is where it starts. To change the data we need to add an event listener to our second select like so
select1.addEventListener('change', function(e) ...
Here is working example. Please read my comments to have better understanding. If you have any questions don't hesitate to ask.
var data = [
{ subject : 'one',
selected: true,
courses: ['Math_one', 'English_one', 'Literature_one']
},
{ subject : 'two',
courses: ['Math_two', 'English_two', 'Literature_two']
},
{ subject : 'three',
courses: ['Math_three', 'English_three', 'Literature_three']
},
{ subject : 'four',
courses: ['Math_four', 'English_four', 'Literature_four']
},
{ subject : 'five',
courses: ['Math_five', 'English_five', 'Literature_five']
},
{ subject : 'six',
courses: ['Math_six', 'English_five', 'Literature_six']
}
];
var select1 = document.getElementById('type_of_subject_c');
var select2 = document.getElementById('course_subj_c');
var resultText = document.getElementById('currentlySelected');
// Your result, do whatever you want
var selectedOptions = [];
function init(data) {
var subjects = [];
for (var i = 0; i < data.length; i++) {
var element = data[i];
// Add subjects to subjects array
subjects.push(element.subject);
// We skip if current element is not selected
if (!element.selected) {
continue;
}
// If element is selected we change content of `select2`
if (element.selected) {
fillSelectOptions(select2, element.courses);
}
}
// Append all subjects as select options to `select1`
fillSelectOptions(select1, subjects);
}
// Lets add event listener `onChange` to `select`
select1.addEventListener('change', function(e) {
// Based on selected/current value we will change data options of `select2`
var selectedValue = e.target.value;
// Clear result text each time we change `select1`
resultText.innerHTML = '';
selectedOptions = [];
// Before we append new data lets clear old one
clearSelect2Options();
// Lets find related data to selected/current value
for (var i = 0; i < data.length; i++) {
var element = data[i];
if (element.subject === selectedValue) {
fillSelectOptions(select2, element.courses);
break;
}
}
});
select2.addEventListener('change', function(e) {
var options = document.querySelectorAll('#course_subj_c option');
resultText.innerHTML = '';
selectedOptions = [];
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.selected) {
selectedOptions.push(option.value);
}
}
// Our Result is :
//console.log(selectedOptions);
// Append result to `resultText` convert array to string via `join()`
resultText.innerHTML = selectedOptions.join();
});
function fillSelectOptions(selector, dataOptions) {
for(var i = 0; i < dataOptions.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = dataOptions[i];
opt.value = dataOptions[i];
selector.appendChild(opt);
}
}
function clearSelect2Options() {
var i;
for(i = select2.options.length - 1 ; i >= 0 ; i--) {
select2.remove(i);
}
}
init(data);
favorite
<select id="type_of_subject_c" name="type_of_subject_c">
</select>
<select name="course_subj_c[]" id="course_subj_c" multiple="multiple" tabindex="1">
</select>
<div>Currently selected <span id="currentlySelected"></span></div>
You can't achieve this just using HTML.
You need to use JavaScript in order to populate the other dropdown with elements depending on the value chose in the first dropdown.
Add an onchange event to the first dropdown.
Inside this function, clear all the option elements of the second dropdown. Then depending on the selected value of the first dropdown, fill the second one. Here an example of code using jQuery.
<select name="first-dropdown" id="first-dropdown" onchange="processValue();">
<option value="" selected="selected">Default Option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="second-dropdown" multiple="multiple" id="second-dropdown">
<option value="" selected="selected">Select option in the first dropdown</option>
</select>
<script type="text/javascript">
function processValue() {
var firstChoice = $('#first-dropdown').val();
// ensure you didn't select the default option
if (firstChoice !== "") {
$('#second-dropdown').empty();
switch (firstChoice) {
case "1":
$('#second-dropdown').append('<option value="first1">First 1</option>');
$('#second-dropdown').append('<option value="first2">First 2</option>');
break;
case "2":
$('#second-dropdown').append('<option value="second1">Second 1</option>');
$('#second-dropdown').append('<option value="second2">Second 2</option>');
break;
// ... other cases
default:
break;
}
// init jquery checkbox plugin again
$('#second-dropdown').multipleSelect();
}
}
</script>
Here the link to jsfiddle:
https://jsfiddle.net/37swkpso/

How to change Selected Index when I only have the name?

I'm integrating Postcode anywhere with my web project. I'm using a drop drop for the county/state field. Postcode anywhere returns the name of the County. Can I change the Selected Index when I only have the name? (I'm using a number for the value field which relates to a database field).
I tried the following:
var f = document.getElementById("state_dropdown");
f.options.[f.selectedIndex].text = response[0].County;
I've tried to include the drop down code html here but I can't get it to work properly for some reason.
But of course this just changes the text field for the item in the drop down that is already selected.
I can query the database and find out what ID I have assigned the county but I'd rather not if there is another way.
Loop over the options until you have a match:
for (var i = 0; i < f.options.length; i++) {
if (f.options[i].text == response[0].Country) {
f.options.selectedIndex = i;
break;
}
}
Demo.
I would make a function and loop over the labels:
See: http://jsfiddle.net/Y3kYH/
<select id="country" name="countryselect" size="1">
<option value="1230">A</option>
<option value="1010">B</option>
<option value="1213">C</option>
<option value="1013">D</option>
</select>​
JavaScript
function selectElementByName(id, name) {
f = document.getElementById(id);
for(i=0;i<f.options.length;i++){
if(f.options[i].label == name){
f.options.selectedIndex = i;
break;
}
}
}
selectElementByName("country","B");
Just a variation on other answers:
<script type="text/javascript">
function setValue(el, value) {
var sel = el.form.sel0;
var i = sel.options.length;
while (i--) {
sel.options[i].selected = sel.options[i].text == value;
}
}
</script>
<form>
<select name="sel0">
<option value="0" selected>China
<option value="1">Russia
</select>
<button type="button" onclick="setValue(this, 'Russia');">Set to Russia</button>
<input type="reset">
</form>

how to set the items selected in a listbox with values provided by an array?

In my apsx page, I have a listbox (techGroups) that has some items that are preselected. The user can change the selections. Meanwhile, I have a reset button. When the user click the reset button, the listbox will be restored with those preselected items selected, while others are not.
I write following javascript function for the reset button's onclientclick. Somehow, after i click the reset button, only the first preselected item get selected, all other preselected items are not.
reset()
{
var selectedGroups = hiddenfield1.value.split(","); //i saved those preselected items in a hiddenfield
for (var i = 0; i < techGroups.options.length; i++) {
for (var j = 0; j < selectedGroups.length; j++) {
if (techGroups.options[i].value == selectedGroups[j]) {
techGroups.options[i].selected = true;
}
}
}
}
Can anybody help me to look at my code and tell me what is wrong? Thanks.
jQuery allowed? if so please see it working here (if not, please disconsider):
http://jsfiddle.net/sW8HX/4/
May be reference issue (DOM). Try this,
JavaScript:
<script type="text/javascript">
window.onload = function () {
var btnReset = document.getElementById("btnReset");
btnReset.onclick = function () {
var hid1 = document.getElementById("hiddenField1");
var techGroups = document.getElementById("techGroups");
var selectedGroups = hid1.value.split(","); //i saved those preselected items in a hiddenfield
for (var i = 0; i < techGroups.options.length; i++) {
for (var j = 0; j < selectedGroups.length; j++) {
if (techGroups.options[i].value == selectedGroups[j]) {
techGroups.options[i].selected = true;
}
}
}
};
};
</script>
Markup:
<form id="form1" runat="server">
<div>
<input type="hidden" id="hiddenField1" value="aa,bb,cc" />
<select id="techGroups" size="4" multiple="multiple">
<option value="rr">rr</option>
<option value="aa">aa</option>
<option value="cc">cc</option>
<option value="zz">zz</option>
<option value="bb">bb</option>
<option value="dd">dd</option>
</select>
<input type="button" id="btnReset" value="Reset" />
</div>
</form>

Move elements from a listbox to another

I have 2 listboxes and when a button is pressed I need to move an option from one to another.
I did this:
HTML
<table border="1" cellpadding="5">
<tr>
<td> Un-Selected <br />
<select multiple="multiple" id="selectBoxOne" size="5" class="selectListBox">
<option value="0" id="multiple0">Option 0</option>
<option value="1" id="multiple1">Option 1</option>
<option value="2" id="multiple2">Option 2</option>
<option value="3" id="multiple3">Option 3</option>
<option value="4" id="multiple4">Option 4</option>
<option value="5" id="multiple5">Option 5</option>
</select>
<br />
<input type="checkbox" id="selectAllFirst" />Select All or Ctrl+Click
</td>
<td>
<div onclick="move('left');">
<< </div>
<div onclick="move('right');"> >></div>
</td>
<td> Selected <br />
<select name="policyCode" multiple="multiple" id="selectBoxSecond" size="5" class="selectListBox"></select>
<br />
<input type="checkbox" id="selectAllSecond" />Select All or Ctrl+Click
</td>
</tr>
</table>
javascript:
// Declare elements
var selectOptions = Array();
selectOptions[0] = "Option 0";
selectOptions[1] = "Option 1";
selectOptions[2] = "Option 2";
selectOptions[3] = "Option 3";
selectOptions[4] = "Option 4";
selectOptions[5] = "Option 5";
// function to move an element from a box to the other
function move(sens)
{
if (sens == "right")
{
var selObj = document.getElementById('selectBoxOne');
var chkAll = document.getElementById("selectAllFirst")
var destination = document.getElementById("selectBoxSecond");
}
else
{
var selObj = document.getElementById('selectBoxSecond');
var chkAll = document.getElementById("selectAllSecond")
var destination = document.getElementById("selectBoxOne");
}
var selectedArray = new Array();
var i;
var count = 0;
if (chkAll.checked == 1)
{
for (i = 0; i<selectOptions.length; i++)
{
selectedArray[i] = i;
}
}
else
{
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
}
for (i = 0; i < selectedArray.length; i++)
{
var optionTag = document.createElement("option");
id = selectedArray[i];
optionTag.innerHTML = selectOptions[id];
optionTag.value = id;
optionTag.id = "multiple"+id;
destination.appendChild(optionTag);
var rmv = document.getElementById("multiple"+id);
rmv.parentNode.removeChild(rmv);
}
}
Now: The script works great from moving from left box to the right box. But when I try the other way around it kind of crashes. No error returned but I know for sure is the removal part (if I comment it it works fine... except that it generates duplicates since there is no removal of the moved option).
To be more specific, this 2 lines:
var rmv = document.getElementById("multiple"+id);
rmv.parentNode.removeChild(rmv);
Since there is no error returned, I don't know how to fix this.
That's a very long winded way of doing things! :-)
You can move an option from one select to another simply by assigning it as a child of the other select, e.g.
function move(sens) {
var i, sourceSel, targetSel;
if (sens == 'right') {
sourceSel = document.getElementById('selectBoxOne');
targetSel = document.getElementById('selectBoxSecond');
} else {
sourceSel = document.getElementById('selectBoxSecond');
targetSel = document.getElementById('selectBoxOne');
}
i = sourceSel.options.length;
while (i--) {
if (sourceSel.options[i].selected) {
targetSel.appendChild(sourceSel.options[i]);
}
}
}
will move all the selected options from one to the other. Note that the while loop goes backwards because the options collection is a live NodeList, so as you remove options is shortens the collection. If you go forwards through it you need to update the index and length as you go (so going backward is simpler).
You may want to include some kind of ordering or sorting (e.g. by value or text).
I guess if the selectAll checkbox is checked you'll just move them all, or (preferably) you could use a click listener to select/deselect all the appropriate optoins when it's clicked independent of the move function.
An id has to be unique, or it won't work properly. As you add the new option before removing the original, you get two options with the same id, and you won't find the original option when you want to remove it.
Just swap these three lines around, so that you remove the option before adding the new one. From this:
destination.appendChild(optionTag);
var rmv = document.getElementById("multiple"+id);
rmv.parentNode.removeChild(rmv);
to this:
var rmv = document.getElementById("multiple"+id);
rmv.parentNode.removeChild(rmv);
destination.appendChild(optionTag);

Categories

Resources