Move elements from a listbox to another - javascript

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);

Related

two html select conflict

I have two html select element that the second one is disabled at first and only become enable if user choose one option from first select. consider we have 2 options in first select -> a , b if user choose a : in the second select options should be : a1,a2 if user choose b : in the second select options should be : b1,b2 ... I dont know what am i doing wrong that these two select options have conflict with each other !!!
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option value="a"> a </option>
<option value="b"> b </option>
</select>
<select id="sub-category" required disabled> </select>
<!-- empty select -->
<script>
document.getElementById("main-category").onchange = function() {
document.getElementById('sub-category').disabled = false;
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "a1";
opt0.innerHTML = "a1";
opt1.value = "a2";
opt1.innerHTML = "a2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
} else if (this.value == 'b') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) { //check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "b1";
opt0.innerHTML = "b1";
opt1.value = "b2";
opt1.innerHTML = "b2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
}
};
</script>
All you need to do is clear out the previous entries in the second drop down every time a selection is made in the first one.
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option value="a"> a </option>
<option value="b"> b </option>
</select>
<select id="sub-category" required disabled> </select>
<!-- empty select -->
<script>
document.getElementById("main-category").onchange = function() {
// Clear out the second list before adding new items to it
document.getElementById('sub-category').innerHTML = "";
// *******************************************************
document.getElementById('sub-category').disabled = false;
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "a1";
opt0.innerHTML = "a1";
opt1.value = "a2";
opt1.innerHTML = "a2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
} else if (this.value == 'b') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) { //check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "b1";
opt0.innerHTML = "b1";
opt1.value = "b2";
opt1.innerHTML = "b2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
}
};
</script>
But, beyond that, your code needs to be cleaned up quite a bit because you shouldn't be scanning the document for the element you want to work with over and over again when you've already found it before. That's extremely wasteful.
Also, .innerHTML is for passing strings that contain HTML so that the HTML parser can parse the string and update the DOM accordingly. You are just setting plain strings with no HTML in them, so you should be using .textContent instead, which doesn't invoke the HTML parser and is more efficient.
Next (just FYI), if you want the value of an option to be the same as the text that is displayed to the user, you don't need to set a value for that option. The value is the contents of the option element by default.
Really, the entire operation can be made so much simpler by simply making new options in list2 based on the first letter of the option chosen in list1.
// Get references to the elements you'll be working with just once:
var list1 = document.getElementById("main-category");
var list2 = document.getElementById('sub-category');
list1.onchange = function() {
list2.disabled = false;
var newHTML = ""; // A string that will contain the new HTML for the second list
// Loop the amount of times we find <option> elements in list one, but start
// at the second one to account for the first one, which isn't really a true choice
for(var i = 1; i < list1.querySelectorAll("option").length; i++){
// Build up a string that the new option should be made from using the
// first character from the option found in list 1
newHTML += '<option>' + list1.value.substr(0,1) + i + '</option>';
}
// By setting a new value for .innerHTML, the old values get thrown out.
list2.innerHTML = newHTML;
};
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option>a</option>
<option>b</option>
</select>
<select id="sub-category" required disabled> </select>

Replace radio buttons with select element using Javascript

I need dynamic script which detects radio button by name and replace it with select element.
These radio buttons can be anywhere in the DOM. I need to distinguish using names and replace it with relevant select-box.
For example input :
<tr>
<td>
Car Type
</td>
<td>
<input type="radio" name="Type"> Old
<input type="radio" name="Type"> New
</td>
</tr>
Required output :
<tr>
<td>
Car Type
</td>
<td>
<select name="Type">
<option value="Old">Old</option>
<option value="New">New</option>
</select>
</td>
</tr>
I tried something, but no success (My Script)
//removing all radio
var radios = document.getElementsByName(name);
for (var i = 0; i < radios.length; i++) {
radios[i].parentNode.removeChild(radios[i]);
}
//replaceing wih select
var selectList = document.createElement("select");
selectList.name = name;
radios[0].parentNode.appendChild(selectList);
//Create and append the options
for (var i = 0; i < data.length; i++) {
var option = document.createElement("option");
option.value = data[i];
option.text = data[i];
selectList.appendChild(option);
}
Plunker full example
I changed a bit your code to make it clearer and functionnal.
I changed document.getElementsByName to document.querySelectorAll in order to have a static NodeList, otherwise you would have to use a while since the collection will reflect changes made when a radio button is removed. You could also remove them later but it would be multiplying for-loops for no reason. Moreover querySelectorAll('input[type="radio"]... focus only on radio buttons, avoiding errors.
I got the label text using .nextSibling to affect it to the option and used trim to remove useless white space and line breaks.
I used remove to remove the radios and labels from the DOM.
As a side note, radio buttons are meant to have a value. You shouldn't rely on the label IMO.
function replaceRadiosBySelect(name) {
var selectList = document.createElement('select'),
radios = document.querySelectorAll('input[type="radio"][name="' + name + '"]');
if (radios.length > 0) {
selectList.name = name;
radios[0].parentNode.appendChild(selectList);
for (var i = 0; i < radios.length; i++) {
var label = radios[i].nextSibling,
option = document.createElement('option');
option.value = option.text = label.data.trim();
selectList.appendChild(option);
radios[i].remove();
label.remove();
}
}
}
replaceRadiosBySelect('Type');
<tr>
<td>
Car Type
</td>
<td>
<input type="radio" name="Type"> Old
<input type="radio" name="Type"> New
</td>
</tr>

JavaScript- Add Selected Option into a list

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>

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>

Select dropdown and auto check the checkbox if the selected value of dropdown is not empty

When people selected the dropdown and then the checkbox will be auto checked if the selected value of dropdown is not empty. But I met "sel[i] is undefined" error.
Javascript part:
var chk = document.getElementsByTagName("input");
var sel = document.getElementsByTagName("select");
for (var i=0; i< sel.length; i++) {
sel[i].onchange = function(){
if (sel[i].value !== ''){
chk[i].checked = true;
}
else{
chk[i].checked = false;
}
};
}
HTML part:
<form name="form1">
<div class="container">
<input id='checkbox_id1' name='checkbox_id1' type='checkbox' value='1' /></label>
Select
<label>
<select id="select_id1" name="select">
<option value=""></option>
<option value="111">111</option>
<option value="222">222</option>
</select>
</label>
<hr>
<input id='checkbox_id2' name='checkbox_id1' type='checkbox' value='1' /></label>
Select
<label>
<select id="select_id2" name="select">
<option value=""></option>
<option value="111">111</option>
<option value="222">222</option>
</select>
</label>
</div>
jsfiddle: http://jsfiddle.net/planetoid/GwEuu/
Your value of i is not what you think it is because the for loop has run to completion before any of the event handlers are actually called, thus i is the value at the end of the forloop.
To capture the appropriate value of i for each event handler, you can use a self executing function like this that captures it in a closure for each specific event handler:
var chk = document.getElementsByTagName("input");
var sel = document.getElementsByTagName("select");
for (var i = 0; i < sel.length; i++) {
(function(i) {
sel[i].onchange = function(){
chk[i].checked = sel[i].value !== '';
}
})(i);
}
Working demo: http://jsfiddle.net/jfriend00/yds6w/
FYI, I've also simplified the .checked assignment code.
But, after looking at your code a bit, I believe this may be a better way of implementing it that doesn't need the self executing function. Rather than rely on perfectly parallel arrays of checkboxes and input tags, this just converts the ID of the select to the ID of the corresponding checkbox and uses this to reference the select element. So, i is not used in the event handler.
var sel = document.getElementsByTagName("select");
for (var i = 0; i < sel.length; i++) {
sel[i].onchange = function(){
var checkboxId = this.id.replace("select_", "checkbox_");
document.getElementById(checkboxId).checked = this.value !== '';
}
}
​
Working demo: http://jsfiddle.net/jfriend00/g3UQG/
I see jfriend00 beat me to it, but you can also use this syntax to achieve the same effect (I also shortened the inner code):
var chk = document.getElementsByTagName("input"),
sel = document.getElementsByTagName("select");
for (var i=0; i< sel.length; i++) {
sel[i].onchange = (function (i) {
return function(){
chk[i].checked = sel[i].value !== '';
};
}(i));
}

Categories

Resources