Want to remove previously appended table - javascript

When I Click on submit button after clicking on the links it appends perfectly but when I hit the button again it doesn't remove previously appended table.
I want to clear the previously created table when user clicks on the cross button and then print the table again or else overwrite the table but instead it is not removing the table and prints a new one.Image Part OneImage Part TwoImage Part ThreeImage Part Four
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(" + i + ")'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
}
//To Remove The Specific Element User Want To Delete
function remove(id) {
orders_list.splice(id, id);
loop("t");
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>

Update your remove function as function remove(el) { el.closest('table').remove(); }.
Update parameter in html as "</td><td onclick='remove(this)'>×</td></tr>".
And add orders_list = []; in the end of loop function.
Try it below.
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(this)'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
orders_list = [];
}
//To Remove The Specific Element User Want To Delete
function remove(el) {
el.closest('table').remove();
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>

Related

How do I send only one message if the second is black, but send two messages if I fill up both variables?

I am adding paragraph tags in a div according to the messages I inputted in the buttons. One of the buttons (HUNT) contains two messages, while the second button (SELL) contains only one. The issue I'm having is that whether the second message is blank or not, I always have an "undefined" message show up.
Here is my code:
function addLog(logBefore, logAfter) {
var par = document.createElement("p");
var node1 = document.createTextNode(logBefore);
var node2 = document.createTextNode(logBefore);
par.appendChild(node1);
var element = document.getElementById("logs");
// Here you can also use element.childNodes.length
const count = document.getElementById("logs").getElementsByTagName("p").length;
if (count >= 8) {
element.removeChild(element.childNodes[0]);
}
element.appendChild(par);
if (node2 != '') {
setTimeout(function addLog(logBefore, logAfter) {
var par = document.createElement("p");
var node2 = document.createTextNode(logAfter);
par.appendChild(node2);
var element = document.getElementById("logs");
// Here you can also use element.childNodes.length
const count = document.getElementById("logs").getElementsByTagName("p").length;
if (count >= 8) {
element.removeChild(element.childNodes[0]);
}
element.appendChild(par);
}, 1000);
};
};
var credits = 0;
var clickPower = 1;
function addCred() {
credits = credits + clickPower;
document.getElementById('credits').innerHTML = credits + " Skatts";
};
#logs {
display: flex;
flex-direction: column-reverse;
}
#logs p {
margin-top: 0px;
}
<div id="credits"></div>
<button onclick="addLog('Hunt begun', 'Hunt successful! You now have ' + credits + ' Skatts'); addCred();">HUNT</button>
<br>
<button onclick="addLog('Resources sold', '')">SELL</button>
<div id="logs"></div>
I got bit confused about your code and what it soupes to do but i belive:
You do not need to to call your timeout function like this:
setTimeout(function addLog(logBefore, logAfter) {
Why even call it again addLog same as parent?? And you do not need to pass values in it as it is nested function that can use your parent values of logBefore an logAfter, so just do:
setTimeout(function () {
Now when you console log values inside timeout you will see values passed and nod2 will be populated.
function addLog(logBefore, logAfter) {
var par = document.createElement("p");
var node1 = document.createTextNode(logBefore);
var node2 = document.createTextNode(logBefore);
par.appendChild(node1);
var element = document.getElementById("logs");
// Here you can also use element.childNodes.length
const count = document.getElementById("logs").getElementsByTagName("p").length;
if (count >= 8) {
element.removeChild(element.childNodes[0]);
}
element.appendChild(par);
if (node2 != '') {
setTimeout(function () {
console.log(logBefore)
console.log(logAfter)
var par = document.createElement("p");
var node2 = document.createTextNode(logAfter);
par.appendChild(node2);
var element = document.getElementById("logs");
// Here you can also use element.childNodes.length
const count = document.getElementById("logs").getElementsByTagName("p").length;
if (count >= 8) {
element.removeChild(element.childNodes[0]);
}
element.appendChild(par);
}, 1000);
};
};
var credits = 0;
var clickPower = 1;
function addCred() {
credits = credits + clickPower;
document.getElementById('credits').innerHTML = credits + " Skatts";
};
#logs {
display: flex;
flex-direction: column-reverse;
}
#logs p {
margin-top: 0px;
}
<div id="credits"></div>
<button onclick="addLog('Hunt begun', 'Hunt successful! You now have ' + credits + ' Skatts'); addCred();">HUNT</button>
<br>
<button onclick="addLog('Resources sold', '')">SELL</button>
<div id="logs"></div>

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

Stop taking input in text-field (tag input)

I am taking some tags name like "study","reading" something like that in the textfield with the help of Bootstrap 4 Tag Input Plugin With jQuery - Tagsinput.js and I have also some predefine tags name contain by buttons. If I click the button then the count of the tag's will increase (count++) and again click this button count will decrease(count--). Same rules for the text-field tags and the total count of the tags in both fields (text and buttons)<=5.
I can count the total tags of the both field but can't stop taking input in text-field when it is greater than 5.
html
<button class="btnr btnr-tags-optional" id="1" onclick="tagSelect(this.id)" >1</button>
<button class="btnr btnr-tags-optional" id="2" onclick="tagSelect(this.id)" >2</button>
<button class="btnr btnr-tags-optional" id="3" onclick="tagSelect(this.id)" >3</button>
My Js
var tagsCount = 0;
var store = 0;
var total_tags = 0;
function tagSelect(clicked_id) {
if (total_tags < 5) {
var tags = document.getElementById(clicked_id);
if (tags.style.borderColor == "rgb(255, 72, 20)") {
tags.style.borderColor = "";
tagsCount--;
} else if (tags.style.borderColor == "") {
tags.style.borderColor = 'rgb(255, 72, 20)';
tagsCount++;
}
total_tags = store + tagsCount;
}
console.log(total_tags);
}
$('#tags_text').on('change', function() {
if (total_tags >= 5) {
$("#tags_text").attr('readonly');
console.log('condition')
} else {
$("#tags_text").removeAttr('readonly');
var items = $("#tags_text").tagsinput('items').length;
store = items;
total_tags = store + tagsCount;
console.log(total_tags);
}
});
Here is the example in jsfiddle
This problem is solved.
I have changed the maxTags value of the plugin with the change of the tags click.
window.tagsCount = 0;
var store = 0;
var total_tags = 0;
function tagSelect(clicked_id) {
var r = ("#" + clicked_id).toString();
if (total_tags < 5) {
if ($(r).hasClass("classActiveIssue")) {
$(r).removeClass("classActiveIssue");
window.tagsCount--;
} else {
$(r).addClass("classActiveIssue");
window.tagsCount++;
}
} else {
if ($(r).hasClass("classActiveIssue")) {
$(r).removeClass("classActiveIssue");
window.tagsCount--;
}
}
total_tags = store + tagsCount;
$("#optionsleft").text(total_tags + "/5 selected");
//console.log("total",total_tags);
}
$('#tags_text').on('change', function() {
var items = $("#tags_text").tagsinput('items').length;
store = items;
total_tags = store + tagsCount;
});
and add the line in add:
self.options.maxTags = 5 - window.tagsCount;
Here is the fiddle

JavaScript - Dynamic To-do list - Editing list

For this To-do list, I am able to add a list. However, once added, I am having issue editing the list that already been added. What I am hoping is when you click Edit, you should able to edit the information and upload the edited information (and making sure the edited information is saved in the local storage when you click Save List to Local Storage). Can someone please help me and go over the JavaScript code and see what I am doing wrong? Below is the HTML, JavaScript and CSS codes:
Here is the Dropbox link if it is easier to download the files: https://www.dropbox.com/sh/qaxygbe95xk4jm1/AADPO98m4416d-ysSGjNt12La?dl=0
<html>
<head>
<title>Dynamic To-do List</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="Dynamic To-do List.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript"></script>
<script src="Dynamic To-do List.js" defer="defer"></script>
</head>
<body onload="loadList();">
<h1>To-Do List</h1> Click Button to Add List: Add List
<div id="listFormDiv">
<form id="addListForm">
List name :
<input type="text" id="listNameTxt"><br />
Description : <textarea name="description" id="listDescTxt"></textarea><br />
Date: <input type="text" id="listDateTxt"><br />
Urgent (Yes or No) :
<select id="listUrgentTxt" name="Urgent">
<option value="Yes"> Yes </option>
<option value="No"> No </option>
</select><br />
Category :
<select id="listCategoryTxt" name="category">
<option value="School"> School </option>
<option value="Work"> Work </option>
<option value="Home"> Home </option>
<option value="Others"> Others </option>
</select>
<input type="button" id="addListBtn" value="Add List" onclick="addList()" />
<input type="button" id="updateListBtn" value="Update List" onclick="updateList()" style="visibility: hidden" />
</form>
</div>
<div id="container">
Save List to Local Storage<br />
Clear Local Storage<br />
<div id="listsDiv">
Add To-Do list here<br />
Hide List<br />
Show List<br />
</div>
</div>
</body>
</html>
sortableList();
$(function() {
$("#listDateTxt").datepicker();
});
function loadList() {
console.log(localStorage.getItem("lists"));
var taskList = JSON.parse(localStorage.getItem("lists"));
if (!taskList) {
console.log("There are no tasks saved in the local storage");
} else {
for (var i = 0; i < taskList.length; i++) {
createListDiv(taskList[i]);
}
}
}
//get a reference to the listFormDiv div tag that has the add To-Do List form. list is a global variable that can be access easily from any function
var listFormDiv = getElement("listFormDiv");
var listArray = Array(); //list will hold all the To-do list added through the form
var listIDCount = 0; // list variable will be incremented every time a list is added and will be used to assing a unique ID to every list object.
if (localStorage.getItem("lists")) {
listArray = JSON.parse(localStorage.getItem("lists"));
}
function clearStorage() {
localStorage.clear();
listArray = [];
}
function getElement(id) {
return document.getElementById(id);
}
//function to show the div with the add to-do list form when the add list hyperlink is clicked onLine
function showListDiv() {
//var st = window.getComputedStyle(listFormDiv,null);
console.log(listFormDiv);
listFormDiv.style.display = "block";
}
//list function adds a list when the "add list" button on the form is pressed - 3rd step
function addList() {
var listName = getElement("listNameTxt").value;
var listDesc = getElement("listDescTxt").value;
var listDate = getElement("listDateTxt").value;
var listUrgent = getElement("listUrgentTxt").value;
var listCategory = getElement("listCategoryTxt").value;
//create an instance of the list object with the values from the form
var f;
if (listCategory == "School") {
f = new schoolTask();
f.setValues(listName, listDesc, listDate, listUrgent, listCategory, "blue");
} else if (listCategory == "Work") {
f = new workTask();
f.setValues(listName, listDesc, listDate, listUrgent, listCategory, "red");
}
console.log("school task is " + JSON.stringify(f));
//clear the textboxes in the form
getElement("listNameTxt").value = "";
getElement("listDescTxt").value = "";
getElement("listDateTxt").value = "";
getElement("listUrgentTxt").value = "";
getElement("listCategoryTxt").value = "";
var listAddButton = getElement("addListBtn");
var listEditButton = getElement("updateListBtn");
console.log(listAddButton);
//listAddButton.style.visibility = "visible";
listEditButton.style.visibility = "hidden";
listFormDiv.style.display = "none";
//add the new list object to the global listArray.
listArray.push(f);
//increment the listID count
listIDCount++;
//add the list to the page and pass in the newly created list object to the createListDiv function
createListDiv(f)
}
// a list object - the second step
function setValues(name, desc, date, urgent, category, color) {
this.name = name;
this.desc = desc;
this.date = date;
this.urgent = urgent;
this.category = category;
this.color = color;
}
function list() {}
//list.prototype.name = "blank name";
list.prototype.name = "blank";
list.prototype.desc = "blank desc";
list.prototype.date = "blank";
list.prototype.urgent = "blank";
list.prototype.category = "blank";
list.prototype.listID = "blank";
list.prototype.color = "blank";
list.prototype.setValues = setValues;
//list.prototype.name = "test";
function schoolTask() {
this.address = "25 Timau Road";
}
inheritFrom(schoolTask, list);
function workTask() {
this.room = "303f";
}
inheritFrom(workTask, list);
function inheritFrom(child, parent) {
child.prototype = Object.create(parent.prototype);
}
//create a div tag to represent the new list and add the new div to the existing place holder div on the page
function createListDiv(list) {
var listDiv = document.createElement("DIV");
listDiv.setAttribute("class", "listClass");
var nameTxt = document.createElement("DIV");
nameTxt.innerHTML = "To-do List Name: " + list.name;
nameTxt.id = "nameTxt" + list.listID;
var lineBreak = document.createElement("BR");
var descTxt = document.createElement("DIV");
descTxt.innerHTML = "Description: " + list.desc;
descTxt.id = "descTxt" + list.listID;
var dateTxt = document.createElement("DIV");
dateTxt.innerHTML = "Date: " + list.date;
dateTxt.id = "dateTxt" + list.listID;
var urgentTxt = document.createElement("DIV");
urgentTxt.innerHTML = "Urgent: " + list.urgent;
urgentTxt.id = "urgentTxt" + list.listID;
var categoryTxt = document.createElement("DIV");
categoryTxt.innerHTML = "Category: " + list.category;
categoryTxt.id = "categoryTxt" + list.listID;
var editLink = document.createElement("A");
editLink.setAttribute("onclick", "editList(" + list.listID + ");"); //Note that we are passing the listID from the list object when calling the editList so we know which list object to fetch to edit when we are editing
editLink.setAttribute("href", "#");
editLink.id = "editLink" + list.listID;
editLink.innerHTML = "Edit";
listDiv.appendChild(nameTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(descTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(dateTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(urgentTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(categoryTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(editLink);
getElement("listsDiv").appendChild(listDiv);
}
//global variable to remember which element in the listArray we are editing
var listIndex;
function editList(listID) {
//get the the list object from the array based on the index passed in
var list;
//show the update list button on the html form and hide the add list button on the same form
var listAddButton = getElement("addListBtn");
var listEditButton = getElement("updateListBtn");
listAddButton.style.visibility = "hidden";
listEditButton.style.visibility = "visible";
//iterate through the listsArray until we find the list object that has the same ID as the id passed in to the function
for (var i = 0; i < listArray.length; i++) {
//if the listID in the list object is the same as the listID passed in to the function then assign the object from the array to the list variable in list function
if (listArray[i].listID == listID) {
//we found the list with the right ID
list = listArray[i];
listIndex = i;
}
}
listFormDiv.style.display = "block";
getElement("listNameTxt").value = list.name;
getElement("listDescTxt").value = list.desc;
getElement("listDateTxt").value = list.date;
getElement("listUrgentTxt").value = list.urgent;
getElement("listCategoryTxt").value = list.category;
//updateList(listIndex);
}
//list function will be called when the update button is pressed on the form
function updateList() {
//save the changed information from the form into the list object in the array based on the array index passed in
listArray[listIndex].name = getElement("listNameTxt").value;
listArray[listIndex].desc = getElement("listDescTxt").value;
listArray[listIndex].date = getElement("listDateTxt").value;
listArray[listIndex].urgent = getElement("listUrgentTxt").value;
listArray[listIndex].category = getElement("listCategoryTxt").value;
var listID = listArray[listIndex].listID; // get the listID from the list object that is in the listsArray at the specificed index;
//now reflect the same changes in the DIV that shows the list
getElement("nameTxt" + listID).innerHTML = "To-do List Name: " + getElement("listNameTxt").value;
getElement("descTxt" + listID).innerHTML = "Description: " + getElement("listDescTxt").value;
getElement("dateTxt" + listID).innerHTML = "Date: " + getElement("listDateTxt").value;
getElement("urgentTxt" + listID).innerHTML = "Urgent: " + getElement("listUrgentTxt").value;
getElement("categoryTxt" + listID).innerHTML = "Category: " + getElement("listCategoryTxt").value;
//reset the listIndex to a value that does not exisit in the array index
listIndex = -1;
var listAddButton = getElement("addListBtn");
var listEditButton = getElement("updateListBtn");
listAddButton.style.visibility = "visible";
listEditButton.style.visibility = "hidden";
//reset form div visibility
listFormDiv.style.display = "none";
getElement("listNameTxt").value = "";
getElement("listDescTxt").value = "";
getElement("listDateTxt").value = "";
getElement("listUrgentTxt").value = "";
getElement("listCategoryTxt").value = "";
}
//Sortable list - http://jqueryui.com/sortable/
function sortableList() {
$("#listsDiv").sortable({
update: function(updateList) {
var sortOrder = getElement(list).sortable('listArray').toString();
console.log(sortOrder);
}
});
}
function saveLists() {
localStorage.setItem("lists", JSON.stringify(listArray));
}
//Hide and Show list
function hideList() {
var listsDiv = getElement("listsDiv");
if (listsDiv.style.display == "block") {
//listsDiv.style.display = "none";
alert("Find a way to hide the list");
}
}
function showList() {
var listsDiv = getElement("listsDiv");
if (listsDiv.style.display == "none") {
listsDiv.style.display = "block";
}
}
#listFormDiv {
border: 1px solid black;
height: 350px;
width: 200px;
position: absolute;
top: 100px;
left: 100px;
padding: 10px;
display: none;
}
#listsDiv { /*Possible #listsDiv*/
height: 350px;
width: 200px;
}
#listDescTxt {
height: 100px;
}
#container {
border: 1px solid black;
height: 650px;
width: 400px;
margin-bottom: 20px;
position: absolute;
top: 100px;
left: 500px;
}
.listClass {
border: 1px solid red;
height: 160px;
width: 200px;
padding: 5px;
}
list.listID is assigned "Blank";
coming from this >
//list.prototype.name = "blank name";
list.prototype.name = "blank";
list.prototype.desc = "blank desc";
list.prototype.date = "blank";
list.prototype.urgent = "blank";
list.prototype.category = "blank";
Line 145: list.prototype.listID = "blank";
list.prototype.color = "blank";
list.prototype.setValues = setValues;
That is why
when it is assigned here >
Line 204: editLink.setAttribute("onclick","editList(" + list.listID + ");");
You click the edit button, it is sending not an *ID but a "blank".
You probably want to reassign the id here >
Line 110: //Assign the id before you push eg. (f.listID == listIDCount++)
//add the new list object to the global listArray.
listArray.push(f);
//increment the listID count
//listIDCount++; why am I incrementing?
//add the list to the page and pass in the newly created list object to the createListDiv function
createListDiv(f)

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

Categories

Resources