How to obtain one by one in IndexedDB - javascript

I am trying to obtain, one by one, the elements in IndexedDB. My target is:
Obtain the first element[key].verbo and adjetivo and sustativo and print in html, to see in the web.
Wait to the user insert a one sentence in what includes these words and click check.
Obtain the second element[key].verbo and adjetivo and sustativo and print in html, to see in the web.
The same as 2.
And continue in the same way.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IndexedDB: Local Database with HTML5</title>
<script type="text/javascript">
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
var dataBase = null;
var pulsador = false;
function startDB() {
dataBase = indexedDB.open('db', 1);
dataBase.onupgradeneeded = function (e) {
var active = dataBase.result;
var object = active.createObjectStore("people", {keyPath: 'id', autoIncrement: true});
object.createIndex('by_adjetivo', 'adjetivo', {unique: false});
object.createIndex('by_verbo', 'verbo', {unique: true});
};
dataBase.onsuccess = function (e) {
alert('Base de datos cargada');
loadAll();
};
dataBase.onerror = function (e) {
alert('Error al cargar Base de datos');
};
}
function add() {
var active = dataBase.result;
var data = active.transaction(["people"], "readwrite");
var object = data.objectStore("people");
var request = object.put({
verbo: document.querySelector("#verbo").value,
adjetivo: document.querySelector("#adjetivo").value,
sustantivo: document.querySelector("#sustantivo").value
});
request.onerror = function (e) {
alert(request.error.adjetivo + '\n\n' + request.error.message);
};
data.oncomplete = function (e) {
document.querySelector('#verbo').value = '';
document.querySelector('#adjetivo').value = '';
document.querySelector('#sustantivo').value = '';
alert('Object successfully added');
loadAll();
};
}
function loadAll() {
var active = dataBase.result;
var data = active.transaction(["people"], "readonly");
var object = data.objectStore("people");
var elements = [];
object.openCursor().onsuccess = function (e) {
var result = e.target.result;
if (result === null) {
return;
}
elements.push(result.value);
result.continue();
};
data.oncomplete = function () {
var outerHTML = '';
for (var key in elements) {
v=elements[key].verbo;
outerHTML+='\n\ <tr>\n\<td>'
+"\t"+"Verbo: \t"+ elements[key].verbo + '</td>\n\<td>'
+"\t"+"Adjetivo: \t"+ elements[key].adjetivo + '</td>\n\ <td>'
+"\t"+"Sustantivo: \t"+ elements[key].sustantivo
+ '</td>\n\ </tr>';
document.querySelector("#elementsList").innerHTML = outerHTML; // I want print one verbo,adjetivo and sustantivo
gradeTest(elements[key].verbo,elements[key].adjetivo,elements[key].sustantivo); //Before, i want
}
elements = [];
};
}
function gradeTest(p1,p2,p3) {
var a1 = document.getElementById('q1').value.toLowerCase();
if(a1.includes(p1) )
if (a1.includes(p2))
if (a1.includes(p3)) {
alert('They are equal');//and we can continue to two elements[key].
}
}
</script>
</head>
<body onload="startDB();">
<input type="text" id="verbo" placeholder="Enter verbo" />
<input type="text" id="adjetivo" placeholder="Enter adjetivo" />
<input type="text" id="sustantivo" placeholder="Enter sustantivo" />
<button type="button" onclick="add();">Save</button>
<hr>
<div id="elements">
<table>
<caption>g</caption>
<thead>
<tr>
<th>Verbo</th>
<th>Adjetivo</th>
<th>Sustantivo</th>
</tr>
</thead>
<tbody id="elementsList">
<tr>
<td colspan="3">Not elements to show</td>
</tr>
</tbody>
<tr>
<td>introduce one verb,adjetive and sustantive</td>
<td><input name="q1" type="text" id="q1" size="30" maxlength="30"/></td>
</tr>
<tr>
<td><input name="submit" type="button" onClick="gradeTest()" value="check"/></td>
</tr>
</table>
</div>

Try creating an array of the items before hand and using a global variable to track the position in the items array. For example:
// Declare a global variable to hold the items
var items = [];
// Open a connection and query for items
function fillItems() {
var openRequest = indexedDB.open('mydb, 1);
openRequest.onsuccess = onOpenConnection;
}
// Query the store for all items
function onOpenConnection(openRequestEvent) {
if(openRequestEvent.type !== 'success' ) {
console.log('connection error');
return;
}
var connection = openRequestEvent.target.result;
var transaction = connection.transaction('mystorename');
var store = transaction.objectStore('mystorename');
var request = store.openCursor();
request.onsuccess = addNextItemFromDatabase;
}
// Add the item at the cursor's current position to the items array,
// and then request the cursor to advance by 1
function addNextItemFromDatabase(event) {
var cursor = event.target.result;
if(cursor) {
items.push(cursor.value);
cursor.continue();
}
}
// When page is loaded, fill the items array
fillItems();
// Global variable that keeps track of index into items array
var currentItemPosition = -1;
// Get the button the user clicks
var button = document.getElementById('mybutton');
// Attach a click listener function that is called whenever the
// button is clicked
button.onclick = function(event) {
// Increment the current position by 1 each time the button
// is clicked
currentItemPosition = currentItemPosition + 1;
// Check if in bounds
if(currentItemPosition >= items.length) {
console.log('out of bounds');
return;
}
// Get the item at the current position
var currentItem = items[currentItemPosition];
console.log(currentItem.verbo);
console.log(currentItem.adjectivo);
// etc..
};

Related

JavaScript arrays adding last element instead of recently added input

Good evening. I am new to JavaScript and I need help with my mini-project and I have only one issue here and it is in the this.Add = function ().
It works properly when I enter a duplicate value from my list therefore it displays an alert that no dupes are allowed. But... when I enter a unique value, it only adds up the last element present (Wash the dishes) from myTasks list. instead of the one I recently entered and the list goes on adding the same ones. Did I just misplace something?
This is my final activity yet and I want to finish it to move to the next function. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tasks CRUD</title>
<style>
#tasks{
display: none;
}
</style>
</head>
<body>
<center>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-task" placeholder="Add another card">
<input type="submit" value="Add">
</form>
<div id="tasks" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-task">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Name</th>
</tr>
<tbody id="myTasks">
</tbody>
</table>
</center>
<script>
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
if (task ) {
for(task of this.myTasks)
{
var ctr = 0;
if(document.getElementById("add-task").value == task){
ctr = 1;
break;
}
}
if(ctr == 1)
{
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task.trim());
// Reset input value
el.value = '';
// Dislay the new list
this.FetchAll();
}
}
};
this.Edit = function (item) {
var el = document.getElementById('edit-task');
// Display value in the field
el.value = this.myTasks[item];
// Display fields
document.getElementById('tasks').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
// Get value
var task = el.value;
if (task) {
// Edit value
self.myTasks.splice(item, 1, task.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item) {
// Delete the current row
this.myTasks.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput() {
document.getElementById('tasks').style.display = 'none';
}
</script>
</body>
</html>
In your for loop:
for (task of this.myTask) {
}
You are not declaring a new task variable, but instead assigning to the outer task variable, hence the repeated addition of tasks already in your list.
You can declare a new variable in the for scope like so:
for (const task of this.myTask) {
}
Your HTML as it is.
And your Javascript goes like below. You have a bug while checking if the task already exists in the array. As you're comparing string value either use simple for loop with triple equals or do as i have attached below.
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
console.log(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
console.log(task);
if (task ){
var arrayContainsTask = (this.myTasks.indexOf(task) > -1);
if(arrayContainsTask == true){
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task);
// Reset input value
el.value = '';
}
// Dislay the new list
this.FetchAll();
}
}
}

Is there way to get the corresponding item using next and next all expression of jquery

I have module regarding getting the right corresponding parent item and parent child, so to get the each item and the child I use the next and nextAll expression of jquery. I will share to you guys my output right now, and the output I want to be.
This is my output right now (Which this output is wrong)
The output should be look like this
My output in my web app. as you can see on my highlighted items there is no children however in my console log when I submit the button the highlighted item repeat the output on the first item ordered
To append the item to that list I use this code.
$("tr#productClicked").click(function () {
var menu_name = $(this).closest("tr").find(".menu_name").text();
var menu_price = $(this).closest("tr").find(".menu_price").text();
var chain_id = $(this).closest("tr").find(".chain_id").text();
var menu_image = $(this).closest("tr").find(".menu_image").attr('src');
swal({
title: "Are you sure to add " + menu_name + " ?",
text: "Once you will add it will automatically send to the cart",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willInsert) => {
if (willInsert) {
swal("Successfully Added to your form.", {
icon: "success",
});
if(chain_id == 0) {
$("tbody#tbody_noun_chaining_order").
append("<tr class='condimentParent' style='background-color:'black !important',color:'white !important' '><td></td><td>"+menu_name+"</td><td class='total'>"+menu_price+"</td><td><button class='removeorderWithOutCondi btn btn-danger form-control'><i class='far fa-trash-alt'></i></button></td></tr>");
}
else
{
$.ajax({
url:'/get_noun_group_combination',
type:'get',
data:{chain_id:chain_id},
success:function(response){
var noun_chaining = response[0].noun_chaining;
$("tbody#tbody_noun_chaining_order").
append("<tr class='condimentParent' style='background-color:'black !important',color:'white !important' '><td></td><td>"+menu_name+"</td><td class='total'>"+menu_price+"</td><td><button class='removeorderWithCondi btn btn-danger form-control'><i class='far fa-trash-alt'></i></button></td></tr>");
$.each(noun_chaining, function (index, el) {
var stringify_noun_chaining = jQuery.parseJSON(JSON.stringify(el));
// console.log(stringify['menu_cat_image']);
var Qty = stringify_noun_chaining['Qty'];
var Condiments = stringify_noun_chaining['Condiments'];
var Price = stringify_noun_chaining['Price'];
var allow_to_open_condiments = stringify_noun_chaining['allow_to_open_condiments'];
var condiments_section_id = stringify_noun_chaining['condiments_section_id'];
$("tbody#tbody_noun_chaining_order").
append("<tr class='editCondiments'>\
<td class='condiments_order_quantity'>"+Qty+"</td>\
<td>*"+Condiments+"</td><td class='total'>"+Price+"</td>\
<td class='allow_to_open_condiments_conditional' style='display:none;'>"+allow_to_open_condiments+"</td>\
<td class='condi_section_id' style='display:none;'>"+condiments_section_id+"</td>\
</tr>");
})
},
error:function(response){
console.log(response);
}
});
}
}
});
This is my add to cart button when inserting the item to the database.
$('button#add_to_cart').on('click',function () {
var customer_id = $('#hidden_customer_id').val();
$parent = $(this).closest("tr.condimentParent");
var menu= $('#noun_chaining_order').find('tr.condimentParent');
menu.next('.condimentParent').add(menu).each(function(){
if(menu.length > 0 ) {
var $tds_menu = $(this).find("td");
Qty_menu = $tds_menu.eq(0).text(),
Item_menu = $tds_menu.eq(1).text(),
Price_menu = $tds_menu.eq(2).text();
console.log(Item_menu);
var condiments= $('#noun_chaining_order').find('tr.editCondiments');
condiments.nextAll('.editCondiments').add(condiments).each(function(){
var $tds_condiments = $(this).find("td");
Qty_condiments = $tds_condiments.eq(0).text(),
Item_condiments = $tds_condiments.eq(1).text(),
Price_condiments = $tds_condiments.eq(2).text();
console.log(Item_condiments);
});
}
});
});
To solved my problem i use multiple add
$('button#add_to_cart').on('click',function () {
var customer_id = $('#hidden_customer_id').val();
$parent = $(this).closest("tr.condimentParent");
var condiments= $('#noun_chaining_order').find('tr.editCondiments');
var menu= $('#noun_chaining_order').find('tr.condimentParent');
menu.next('.condimentParent').add(menu).add(condiments).each(function(){
var $tds_menu = $(this).find("td");
Qty_menu = $tds_menu.eq(0).text(),
Item_menu = $tds_menu.eq(1).text(),
Price_menu = $tds_menu.eq(2).text();
console.log(Item_menu);
// condiments.nextAll('.editCondiments').add(condiments).each(function(){
// var $tds_condiments = $(this).find("td");
// Qty_condiments = $tds_condiments.eq(0).text(),
// Item_condiments = $tds_condiments.eq(1).text(),
// Price_condiments = $tds_condiments.eq(2).text();
// console.log(Item_condiments);
// });
});
});

Google Chrome Local Storage Adding Links

So I'm trying to add an option on my options page for people to set 1-3 letters as a link to a website. Currently I'm getting a NaN value for the linkNumber when I run the function.
The Function:
function addLink () {
chrome.storage.local.get('linkNumber', function (x) {
if (x.linkNumber == undefined) {
chrome.storage.local.set({'linkNumber': '0'}, function() {
addLink();
});
} else {
var linkNumberInteger = parseInt(x.linkNumber);
var handle = document.getElementById("short");
var link = document.getElementById("long");
var handleValue = handle.value;
var linkValue = link.value;
var handleNumber = x.linkNumber + '-handle';
var urlNumber = x.linkNumber + '-link';
var objectOne = {};
var objectTwo = {};
objectOne[handleNumber] = x.linkNumber + '-handle';
objectTwo[urlNumber] = x.linkNumber + '-link';
console.log(x.linkNumber);
console.log(handleNumber);
chrome.storage.local.set({handleNumber: handleValue}, function(y) {
console.log(y.handleNumber + ' handle saved');
});
chrome.storage.local.set({urlNumber: linkValue}, function(z) {
console.log(z.handleNumber + ' link saved');
});
var linkNumberIntegerNext = linkNumberInteger++;
var n = linkNumberIntegerNext.toString();
chrome.storage.local.set({'linkNumber': n}, function() {
});
alert('Link Added');
}
});
}
The Html:
<h3 class="option">Add Quick Link:</h3>
<input contenteditable="true" type="text" class="short-quicklink" id="short" maxlength="3">
<span>http://</span><input contenteditable="true" type="text" class="long-quicklink" id="long">
<button class="add">Add Quick Link</button>

Dynamic Div ID and Creating Elements Inside it

I am creating a dynamic Div where i can import values from the showModalDialog when it is closed. So after closing the modal, i get couple of values.
What i am trying to do here is:
I have couple of dynamic div's and against each div, i have a link to open a window.
After selection of the files they are return back to the parent window as comma separated.
I want to insert those values inside the div to which that popup was opened. but in this scenario i am facing the trouble. the Divid's are generated dynamically
Here is the Complete Code for Javascript + Jquery Based, I am getting the following error.
TypeError: theDiv.appendChild is not a function
[Break On This Error]
theDiv.appendChild(newNode);
<script type="text/javascript" src="JS/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function eliminateDuplicates(arr,divID)
{
var i,
len=arr.length,
out=[],
obj={};
for (i=0;i<len;i++)
{
obj[arr[i]]=0;
}
for (i in obj)
{
out.push(i);
}
return out;
}
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
Test= function(str,divID)
{
var arrID = new Array();
arrID = str.split(',');
arrID = eliminateDuplicates(arrID);
var theDiv = $("#projectsList"+divID).attr('id'); //document.getElementById('projectsList');
alert(theDiv);
var cmp= $("#projectIDS"+divID).val(); //document.getElementById("projectIDS").value;
var cnp = $("#countProj"+divID);//document.getElementById("countProj")
var cproj;
if(cnp.val().length == 0)
cproj=0;
else
cproj=parseInt(cnp.val());
for (var j=0; j<arrID.length; j++)
{
if (parseInt(cproj) + 1 > 50)
{
alert("You cannot add more than 50 Project id's ");
return;
}
if( cmp!="" && cmp.indexOf(arrID[j])!=-1)
continue;
var newNode = document.createElement('div');
newNode.style.cssText = "background:#CCCCCC;border:1px solid #666666;width:100px;word-wrap:break-word;margin:3px;float:left;color:black;text-decoration:none!important;height:auto;vertical-align:middle;padding-top:2px;";
newNode.title = arrID[j]+" ";
newNode.innerHTML = '<input type=hidden name=Proj_' + j + ' ' + 'value=' + arrID[j] + '>' + arrID[j] + ' <b>X</b>';
theDiv.appendChild(newNode);
if(cmp.length == 0)
{
//document.getElementById("projectIDS").value=arrID[j]
$("#projectIDS"+divID).val(arrID[j]);
}
else
{
//document.getElementById("projectIDS").value = document.getElementById("projectIDS").value+","+arrID[j];
$("#projectIDS"+divID).val($("#projectIDS"+divID).val()+","+arrID[j]);
}
cproj = parseInt(cproj)+1;
//document.getElementById("countProj").value =cproj;
cnp.value(cproj);
}
}
removetext = function(par)
{
var strremove=par.text();
var strexist = document.getElementById("projectIDS").value;
strremove = strremove.replace(" X","");
tempRemove(strexist, strremove);
par.remove();
var cproj;
if(document.getElementById("countProj").value.length == 0)
cproj=0;
else
{cproj=parseInt(document.getElementById('countProj').value);
cproj=parseInt(cproj)-1;}
document.getElementById("countProj").value =cproj;
}
function tempRemove(strexist,strremove)
{
var b = strexist.indexOf(strremove);
var after = strexist.indexOf(",",b);
var newstrexist;
var before = strexist.lastIndexOf(",",b);
if(after!=-1)
{newstrexist=strexist.replace(strremove+',',"");}
else if(before!=-1)
{newstrexist=strexist.replace(','+strremove,"");}
else
{newstrexist= strexist.replace(strremove,"");}
document.getElementById("projectIDS").value=newstrexist;
//remove current friend
}
function openWindow(divID)
{
var lookUpAlys=window.showModalDialog("files.cfm?d=" + Math.random() + '&fileID=' + divID,window,"center=yes;dialogWidth:895px:dialogHeight:785px;status:no");
if(lookUpAlys.forename!=undefined)
{
var temp = lookUpAlys.forename;
Test(temp,divID);
}
}
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="2" cellpadding="1">
<tr>
<td>Choose</td>
<td>Files</td>
<td>Action</td>
</tr>
<cfloop from="1" to="5" index="i">
<cfoutput>
<tr>
<td><input type="checkbox" name="getFile" id="getFile" value="#i#" /></td>
<td><div id="projectsList#i#" style="width:500px;height:60px;overflow-y:scroll;border:1px solid gray;"></div><input type="text" name="projectIDS#i#" id="projectIDS#i#" data-id="#i#" value="" /><input type="text" data-id="#i#" name="countProj#i#" id="countProj#i#" value="" /></td>
<td>Files</td>
</tr>
</cfoutput>
</cfloop>
</table>
</body>
</html>
so my apologies if i had entered the code incorrectly. Basically trying do it Classic Javascript Way
This does not do what I think you think it does:
var theDiv = $("#projectsList"+divID).attr('id'); //document.getElementById('projectsList');
You should do
var theDiv = $("#projectsList"+divID)[0];
to get the DOM element.
Or, for this scenario, just do
var theDiv = document.getElementById("projectsList" + divID);
Also, I'm not sure why you are mixing raw DOM operations and jQuery wrapped operations everywhere. Just stick to one of them, and be consistent.
var container = $('.itemsList');
var divSubmit = $(document.createElement('div'));
//assigning id to div
$(divSubmit).attr('id','itemTemplate');
$(divSubmit).css({"font-family":"Gotham, Helvetica Neue, Helvetica, Arial, sans-serif","position":"relative","height": "70px","clear" : "both","background-color":"#FFF","border-bottom": "0.09em solid #EBEBEB"});
//adding class to main container
$(divSubmit).addClass('itemTemplate');
//adding Child's name label and assigning id to it.
var Name = '<label class="lblName" id="lblName" for="Name">'+getName()+'</label>';
$(divSubmit).append(Name);
$(divSubmit).append(container);
Here's a sample code. first of all there is sample container called itemslist
that will contain the generated div.
divSubmit will be gernerate dynamically and append to container.
To find some div for click event. Lets say we want to get child name.
alert($($(this).find("label.lblName")).val());

Switching menu items between two lists using buttons in 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");
}

Categories

Resources