Switching menu items between two lists using buttons in JavaScript - javascript

I have this school assignment that I've been working on and am totally stumped as to why it's doing what it's doing. Basically it's a left selection list, 2 middle buttons, and a right selection list. The purpose is to move options between lists. My problem is as follows: a selection is made on left list, the move to right list button is clicked, an option is added to the right list named "undefined" and the selection on the left list disappears. I don't want anyone to do my homework for me, but tips and hints are greatly appreciated.
Here's my code:
<script type="text/javascript">
/* <![CDATA[ */
function moveRight() {
var leftCurText = document.forms[0].leftSide.selectedIndex.text;
var leftCurValue = document.forms[0].leftSide.selectedIndex.value;
var leftCurName = document.forms[0].leftSide.selectedIndex;
if (leftCurName != -1) {
var listName = new Option();
listName.text = leftCurText;
listName.value = leftCurValue;
nextItem = document.forms[0].rightSide.length;
document.forms[0].rightSide.options[nextItem] = listName;
document.forms[0].leftSide.options[leftCurName] = null;
} else if (document.forms[0].leftSide.length <= 0) {
window.alert("There are no more options in the left list")
}
else
window.alert("No option is selected on the left side");
}
function moveLeft() {
var rightCurText = document.forms[0].rightSide.selectedIndex.text;
var rightCurValue = document.forms[0].rightSide.selectedIndex.value;
var rightCurName = document.forms[0].rightSide.selectedIndex;
if (rightCurName != -1) {
var listName = new Option();
listName.text = rightCurText;
listName.value = rightCurValue;
nextItem = document.forms[0].leftSide.length;
document.forms[0].leftSide.options[nextItem] = listName;
document.forms[0].rightSide.options[rightCurName] = null;
} else if (document.forms[0].rightSide.length <= 0) {
alert("There are no more options on the right list")
} else
window.alert("No option is selected on the right side");
}
/* ]]>*/
</script>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link rel="Stylesheet" type="text/css" />
</head>
<body>
<h2>This page will switch items between lists</h2>
<div align="center">
<form action="">
<table border="3">
<tr>
<th>Left List</th>
<th>Click</th>
<th>Right List</th>
</tr>
<tr>
<td>
<select name="leftSide" size="6">
<option value="stephanie">Stephanie</option>
<option value="beatriz">Beatriz</option>
<option value="carol">Carol</option>
</select>
</td>
<td>
<input type="button" onclick="moveLeft()" name="leftButton" value="<<" /> <br />
<input type="button" onclick="moveRight()" name="rightButton" value=">>" />
</td>
<td>
<select name="rightSide" size="6">
<option value="evan">Evan</option>
<option value="david">David</option>
<option value="mark">Mark</option>
</select>
</td>
</tr>
</table>
</form>
</div>
</body>

You are trying to get properties from the selectedIndex property of the list, which is a number. You want to get it from theList.options[theList.selectedIndex].
EDIT:
Also, your variables are named rather confusingly. Try this:
var list = document.forms[0].rightSide;
var index = list.selectedIndex;
var text = list.options[index].text;
var value = list.options[index].value;
And one of the most striking things: your two functions are basically the same. Give the source list and target list as parameters to a general move() function.

Idk why the code is so messed up. Here's the functions:
Move Left:
function moveLeft() {
var rightCurText = document.forms[0].rightSide.selectedIndex.text;
var rightCurValue = document.forms[0].rightSide.selectedIndex.value;
var rightCurName = document.forms[0].rightSide.selectedIndex;
if (rightCurName != -1) {
var listName = new Option();
listName.text = rightCurText;
listName.value = rightCurValue;
nextItem = document.forms[0].leftSide.length;
document.forms[0].leftSide.options[nextItem] = listName;
document.forms[0].rightSide.options[rightCurName] = null;
}
else if (document.forms[0].rightSide.length <= 0) {
alert("There are no more options on the right list")
}
else
window.alert("No option is selected on the right side");
}
Move Right:
function moveRight() {
var leftCurText = document.forms[0].leftSide.selectedIndex.text;
var leftCurValue = document.forms[0].leftSide.selectedIndex.value;
var leftCurName = document.forms[0].leftSide.selectedIndex;
if (leftCurName != -1) {
var listName = new Option();
listName.text = leftCurText;
listName.value = leftCurValue;
nextItem = document.forms[0].rightSide.length;
document.forms[0].rightSide.options[nextItem] = listName;
document.forms[0].leftSide.options[leftCurName] = null;
}
else if (document.forms[0].leftSide.length <= 0) {
window.alert("There are no more options in the left list")
}
else
window.alert("No option is selected on the left side");
}

Related

Input value is not changed on Javascript

I make shopping Cart now with vanilla javascript, html, css.
This program is when consumer click selection tag, add new tag and change count.
To Add new Tag is already working. Change count is not work. When I clicked, selectA, selectB, selectC is changed but not working on input tag.
var selectA = 0;
var selectB = 0;
var selectC = 0;
function handleOnChange(e) {
// 선택된 데이터 가져오기
let value = e.value;
let name = e.options[e.selectedIndex].text;
let itemList = document.getElementById("addItem");
var Item = document.createElement('div');
var itemName = document.createElement('div');
var itemSumA = document.createElement('input');
var itemSumB = document.createElement('input');
var itemSumC = document.createElement('input');
itemName.innerHTML = name;
if (value === "A") {
if (selectA === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumA);
itemList.appendChild(Item);
}
itemSumA.value = selectA;
} else if (value === "B") {
console.log(selectB);
if (selectB === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumB);
itemList.appendChild(Item);
}
itemSumB.value = ++selectB;
} else {
if (selectC === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumC);
itemList.appendChild(Item);
}
itemSumC.value = ++selectC;
}
document.getElementById("Sum").innerHTML = selectA * 39800 + selectB * 49800 + selectC * 59800;
}
<li class="checked">
<button class="accordion">주문 정보</button>
<div class="panel">
<p>상품 선택</p>
<select name="tent" id="tent" onchange="handleOnChange(this)">
<option value="A">A. 스피드 원터치 팝업텐트(3~4인용)</option>
<option value="B">B. 5초 원터치 텐트(3인용) (+10,000)</option>
<option value="C">C. 5초 원터치 텐트(5인용) (+20,000)</option>
</select>
<div id="addItem"></div>
</div>
</li>
I want to know why.

Having trouble with displaying an image through an array

I am practicing with JavaScript Array function. What I want to achieve is to show google embedded images inside the display section when the user clicks "Show my grocery list" button after entering "banana", else the texts will be shown instead.
These are my codes.
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup",function(ev){
if(ev.keyCode == 13){
groceryList.push(grocery.value);
console.log("array",groceryList);
}
});
showItems.addEventListener("click",function(){
for (var i = 0; i < groceryList.length;i++){
if(groceryList[i] == "banana"){
display.src = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
#display {
width:100px;
height:100px;
}
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery"/>
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
It is currently not showing anything. I have a feeling that I have written a wrong syntax inside the loop function? I would appreciate a solution and tips. Thank you.
You've to remove the keyCode=13 condition first and then need to create an img element with src of image based on condition (groceryList[i] == "banana") to display the image inside the <div> element, For example:
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup", function(ev) {
//if(ev.keyCode == 13){
groceryList.push(grocery.value);
//console.log("array",groceryList);
//}
});
showItems.addEventListener("click", function() {
for (var i = 0; i < groceryList.length; i++) {
if (groceryList[i] == "banana") {
var source = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
var img = document.createElement("IMG"); //create img element
img.src = source; //set img src
display.appendChild(img); // display image inside <div>
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery" />
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>

Drop down box text disappears after completing a function, how can I get it to display what option was chosen?

The functions below work fine, the only thing I need help with is that when I pick an option from a drop down menu, it runs the function, but it erases all of the options in the drop down box. How can I get it NOT to do that and continue displaying my original options in the same drop down box?
<script type="text/javascript">
function gbid(s) {
return document.getElementById(s);
}
function myCount() {
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("somefilepathhere.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var agent,count
agent=document.getElementById("tAgent").value;
if (agent=="Agent1")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(1,1).Value;
}
else if (agent=="Agent2")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(2,1).Value;
}
document.getElementById("disphere").innerHTML = count;
excel.Quit();
excel.Application.Quit();
}
function saveToExcel() {
var myApp = new ActiveXObject("Excel.Application");
myApp.visible = false;
var xlCellTypeLastCell = 11;
var x = document.forms["f1"]["tAgent"].value;
if (x == null || x == "") {
alert("You must select an 'Entered By' option!");
return false;
}
else
var myWorkbook = myApp.Workbooks.Open(filePath);
var myWorksheet = myWorkbook.Worksheets(1);
myWorksheet.Activate;
objRange = myWorksheet.UsedRange;
objRange.SpecialCells(xlCellTypeLastCell).Activate;
newRow = myApp.ActiveCell.Row + 1;
alert('A new log was created on row '+newRow);
strNewCell = "A" + newRow;
myApp.Range(strNewCell).Activate;
myWorksheet.Cells(newRow,1).value = f1.tMemberid.value;
myWorksheet.Cells(newRow,2).value = f1.tDate.value;
myWorksheet.Cells(newRow,3).value = f1.tRep.value;
myWorksheet.Cells(newRow,4).value = f1.tIssuerep.value;
myWorksheet.Cells(newRow,5).value = f1.tLOB.value;
myWorksheet.Cells(newRow,6).value = f1.tContactnum.value;
myWorksheet.Cells(newRow,7).value = f1.tMembername.value;
myWorksheet.Cells(newRow,8).value = f1.tIssid.value;
myWorksheet.Cells(newRow,9).value = f1.tTypeofissue.value;
myWorksheet.Cells(newRow,10).value = f1.tDiscofissue.value;
myWorksheet.Cells(newRow,11).value = f1.tTimesent.value;
myWorksheet.Cells(newRow,12).value = f1.tSendto.value;
myWorksheet.Cells(newRow,13).value = f1.tAgent.value;
myWorkbook.Close(true);
myApp.Workbooks.Close;
myApp.Close;
alert('Process Complete!');
}
</script>
<table >
<tr>
<td class="tb_bor" Align="center" ><h1>ACA Issues Tracker</h1><br />
<b>Entered By: </b>
<select name="tAgent" id="tAgent" style="80% !important;" onchange="myCount()">
<option value="" ></option>
<option value="Agent1" >Agent 1</option>
<option value="Agent2" >Agent 2</option>
</select>
<br />You have completed: <p id="disphere"></p>
<hr>
</td>
</tr>
</table>
With the below line you overwrite the inner text of your select field:
count = gbid( 'tAgent' ).innerText = excel_sheet.Cells( 1,1 ).Value;
^
|
Allthough I'm not clear on what you desire to achieve with the code because I don't understand your usecase, I think you might have mistaken the second equals sign with a string concatenation or something?
This might be what you tried to achieve:
count = gbid( 'tAgent' ).innerText + ' ' + excel_sheet.Cells( 1,1 ).Value;
This is a corrected version of your function:
function myCount() {
var excel = new ActiveXObject( 'Excel.Application' ),
excel_file = excel.Workbooks.Open( 'somefilepathhere.xlsx' ),
excel_sheet = excel.Worksheets( 'Sheet1' ),
agent = document.getElementById( 'tAgent' ).value,
count;
if ( agent === 'Agent1' ) {
count = excel_sheet.Cells( 1,1 ).Value;
} else if ( agent === 'Agent2' ) {
count = excel_sheet.Cells( 2,1 ).Value;
}
document.getElementById( 'disphere' ).innerHTML = count;
excel.Quit();
excel.Application.Quit();
}

Javascript Dynamic Table

I'm having trouble the following table should read r1 c1, r1 c2, r2 c1, r2 c2 and so on in each box within the table and user should only be able to pick up to 12 rows and 12 columns anything over that should display an error message. Here is my code so far.
<!DOCTYPE html>
<!-- written by Angela Bauer on 1/23/2013-->
<!-- saved from url=(0014)about:internet -->
<html>
<head>
<meta charset = "utf-8">
<title> Dynamic Table </title>
<script type = "text/javascript">
var width = 500;
var height = 500;
function CreateTable(txtRows, txtCols, hold)
{
if(validNumber(txtRows) && validNumber(txtCols)
&& (hold != null) && (hold.canHaveChildren))
{
hold.innerHTML = "";
var table = document.createElement("table");
table.border = 3;
table.borderColor = "Blue";
table.height = height;
table.width = width;
var row = null;
var cell = null;
hold.appendChild(table);
for(i=0; i<txtRows; i++)
{
row = appendR(table)
for(j=0; j<txtCols; j++)
{
cell = appendC(row);
cell.innerText = j;
cell = null;
}
row = null;
}
}
}
function appendR(table)
{
if(table != null)
{
return table.insertRow();
}
else
{
alert("Error while creating table. Cause: Container Table is null!");
}
}
function appendC(aRow)
{
if(aRow != null)
{
return aRow.insertCell();
}
else
{
alert("Error while creating table. Cause: Container row is null!");
}
}
function validNumber(ipNum)
{
if(isNaN(ipNum))
{
alert("Invalid Number!");
return false;
}
else if(ipNum <= 1)
{
alert("You can only enter a number from 1 - 12!");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<table>
<tr>
<td> How many Rows would you like: </td>
<td><input type=text name=txtRows value=1 /></td>
</tr>
<tr>
<td> How many Columns would you like: </td>
<td><input type=text name=txtCols value=1 /> </td>
</tr>
<tr>
<td colspan=10 align=right><input type=button name=cmdCreate value="Create Table"
onClick="CreateTable(txtRows.value, txtCols.value, divHolder)" /></td>
</tr>
</table>
<div id=divHolder></div>
</body>
</html>
As gdoron put you need to ask a question but im taking a punt and guess you want you code fixed.
Below is a working copy of you code. There was a ton of stuff wrong including
No ID's on the input boxes
No " used for the value of items within the HTML form
.insertRow was missing a parameter
.insertCell was missing a parameter
The validNumber function was producing an error if you entered the
number 1.
canHaveChildren is only valid in IE i have removed it but if your
script is going to be used in IE only then add it back
Things to be avoid for best practice:
using the words table, row etc as var names.
I guessing your new at this so my advice is to install Firefox and the firebug add on as it would have told you half the errors you were getting.
Also if its not doing what you want add alerts to sections of the code and work out where it is getting to or not getting to.
Hopefully this will get you on track.
<html>
<head>
<meta charset = "utf-8">
<title> Dynamic Table </title>
<script type = "text/javascript">
var width = 500;
var height = 500;
function createTable(txtRows, txtCols, hold) {
// alert (txtRows+", "+txtCols+", "+hold);
// alert (hold.canHaveChildren);
// Removed as its an IE only javascript ---- && (hold.canHaveChildren)
if(validNumber(txtRows) && validNumber(txtCols) && (hold != null) ) {
// alert ("is valid");
hold.innerHTML = "";
var table1 = document.createElement("table");
table1.border = 3;
table1.borderColor = "Blue";
table1.height = height;
table1.width = width;
var row1 = null;
var cell1 = null;
hold.appendChild(table1);
for(i=0; i<txtRows; i++) {
// alert ("first for");
row1 = appendR(table1, i);
for(j=0; j<txtCols; j++) {
// alert ("second for");
cell1 = appendC(row1, j);
cell1.innerText = j;
cell1 = null;
}
row1 = null;
}
}
}
function appendR(table1, i) {
if(table1 != null) {
return table1.insertRow(i);
} else {
alert("Error while creating table. Cause: Container Table is null!");
}
}
function appendC(aRow, j) {
if(aRow != null) {
return aRow.insertCell(j);
} else {
alert("Error while creating table. Cause: Container row is null!");
}
}
function validNumber(ipNum) {
if(isNaN(ipNum)) {
alert("Invalid Number!");
return false;
} else if(ipNum > 12) {
alert("You can only enter a number from 1 - 12!");
return false;
} else if(ipNum < 1) {
alert("You can only enter a number from 1 - 12!");
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<table>
<tr>
<td> How many Rows would you like: </td>
<td><input id="txtRows" type="text" name="txtRows" value="1" /></td>
</tr>
<tr>
<td> How many Columns would you like: </td>
<td><input id="txtCols" type="text" name="txtCols" value="1" /> </td>
</tr>
<tr>
<td colspan=10 align=right><input type=button name=cmdCreate value="Create Table"
onClick="createTable(txtRows.value, txtCols.value, divHolder)" /></td>
</tr>
</table>
<div id="divHolder"></div>
</body>

Elements added using jquery to table inside of form are not posting

I have written the following code to dynamically build a table that will then be sent to a server and passed on through email. However, when the user posts the data it is not posting, any of the items in the dropdown fields. I did a lot of research and i think it has to do with the DOM, but I'm not sure of how to fix it.
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
var row_counter = 1
var sandwichOptions = { '' : 'None',
'item1' : 'Item1',
'item2' : 'Item2',
'item3' : 'Item3',
'item4' : 'Item4'
};
function createTable(tbody, rows, cols) {
if (tbody == null || tbody.length < 1) return;
if ($('#body') != null) {$('#body').empty()};
for (var r = 1; r <= rows; r++) {
var trow = $("<tr>");
var sandwich = $('#sandwiches').clone();
sandwich.name = "sandwich"+r;
// var sandwich = $('<select></select>');
// //sandwich.attr("id","sandwich"+r);
// sandwich.name = "sandwich"+r;
// sandwich.append(new Option('Foo', 'foo', true, true));
// $.each(sandwichOptions, function(val, text)
// {sandwich.append(new Option(text, val, true, true))}); //, {value: "Item1", text: "Item1"}));
var salads = $('#salads').clone();
salads.name = "salads"+r;
var dessert = $('#dessert').clone();
dessert.name = "dessert"+r;
var name_input = document.createElement('input');
name_input.type = 'text';
name_input.name = "name_input"+r;
var special_request = document.createElement('input');
special_request.type = 'text';
special_request.name = "special_request"+r;
trow.append($("<td>").text(r));
trow.append($("<td>").append(name_input));
trow.append($("<td>").append(sandwich.show()));
trow.append($("<td>").append(salads.show()));
trow.append($("<td>").append(dessert.show()));
trow.append($("<td>").append(special_request));
trow.attr("id","row"+r);
tbody.append(trow)
}
}
function add_row(tbody) {
var r = row_counter
var trow = $("<tr>");
var sandwich = $('#sandwiches').clone();
sandwich.name = "sandwich"+r;
var salads = $('#salads').clone();
salads.name = "salads"+r;
var dessert = $('#dessert').clone();
dessert.name = "dessert"+r;
var name_input = document.createElement('input');
name_input.type = 'text';
name_input.name = "name_input"+r;
var special_request = document.createElement('input');
special_request.type = 'text';
special_request.name = "special_request"+r;
trow.append($("<td>").text(r));
trow.append($("<td>").append(name_input));
trow.append($("<td>").append(sandwich.show()));
trow.append($("<td>").append(salads.show()));
trow.append($("<td>").append(dessert.show()));
trow.append($("<td>").append(special_request));
trow.attr("id","row"+r);
trow.appendTo(tbody);
}
$(document).ready(function() {
table = $('form #order_table');
$('#refresh').click(function() {
//you can simplify the code by making the addition or deletion of rows triggered
var value = $('#CustNum').val();
$('#refresh').val("Clear/Reset Form");
createTable(table, value, 5);
row_counter = value;
table.show();
$('#add_row').show();
//$('#delete_row').show();
$('#email').show();
$('#send_button').show();
$('#row_count').text(row_counter);
});
$('#add_row').click(function() {
row_counter = parseInt(row_counter) + 1;
add_row(table);
$('#CustNum').val(row_counter);
$('#row_count').text(row_counter);
});
$('#delete_row').click(function() {
//if (row_counter == 1) return;
$('#row'+row_counter).remove();
row_counter = parseInt(row_counter) - 1;
$('#CustNum').val(row_counter);
$('#row_count').text(row_counter);
});
$(document).click(function() {
if (parseInt(row_counter) > 1) {$('#delete_row').show()}
else {$('#delete_row').hide()};
});
$('#CustEmail').focus(function() {
if ($('#CustEmail').val() == 'email') {$('#CustEmail').val('')
.css('color','#000000')
.css('font-style','normal')
};
});
$('#CustEmail').blur(function() {
if ($('#CustEmail').val() == '') {$('#CustEmail').val('email')
.css('color','#A0A0A0')
.css('font-style','italic')
};
});
});
<form id = "testxx" method = "post">
enter number of customers:
<input type="number" name = "CustNum" id = "CustNum" value=1 min=1>
<input type="button" value="Generate Form" id="refresh">
<input type="button" value="Add Row" id="add_row" style ="display: none;">
<input type="button" value="Delete Row" id="delete_row" style ="display: none;">
<table id="order_table" style="display: none;" name = "test">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Sandwich</th>
<th>Salad</th>
<th>Dessert</th>
<th>Special Requests<th>
</tr>
</thead>
<tbody id = "body">
</tbody>
</table>
<select id="sandwiches" style="display: none;">
<option>None</option>
<option value = "Option1">Option1</option>
<option value = "Option2">Option2</option>
<option value = "Option3">Option3</option>
<option value = "Option4">Option4</option>
</select>
<select id="salads" style="display: none;">
<option>None</option>
<option value = "Option1">Option1</option>
<option value = "Option2">Option2</option>
<option value = "Option3">Option3</option>
<option value = "Option4">Option4</option>
</select>
<select id="dessert" style="display: none;">
<option>None</option>
<option value = "Option1">Option1</option>
<option value = "Option2">Option2</option>
<option value = "Option3">Option3</option>
<option value = "Option4">Option4</option>
</select>
When an Element is hidden, it is not submited with the form.
delete the display:none of your select to submit.
Thanks, I was able to figure it out.
I did a couple of things to correct. I put the select statements inside of the form tags, I changed the table var to be table = $('#body') - the id for tbody. and I changed the naming code from 'X'.name = 'Y' to the jquery method 'X'.attr('name','Y').
Between all of those changes it finally works. Thanks.

Categories

Resources