This is my todo list based on the Module Pattern, this is working fine and just want to know two things.
Is this code still can be simplified?
Once I added a list, if i refresh the page, then, these list are gone, but, my requirement is, these lists are deleted when i use 'Remove List'. How I can amend this? Any advise?
<!DOCTYPE html>
<html>
<head>
<title> TO-Do List In Javascript </title>
<style>
#message{
left: 0px;
margin-left: 10px;
}
div#todo > div input {
top:-39px;
margin-left: 226px;
position: relative;
}
div#todo > div > p {
padding: 0px;
width: 210px;
}
div#todo div {
top:0px;
padding:0px;
margin:0px;
}
</style>
</head>
<body>
<div id="itemin"><input type="text" id="txt1" name="text1"/><input type="button" id="bt1" value="Add List"/><input type="button" id="bt2" value="Remove List"/></div>
<div id="todo">
</div>
<script type="text/javascript">
var Todo = Todo || {};
var element = document.getElementById("todo");
var elementChiCount="";
Todo.Item = (function(){
function creatList(someInput) {
elementChiCount = element.getElementsByTagName("div").length;
var txtNode = document.createTextNode(someInput);
var elemNode = document.createElement("p");
elemNode.appendChild(txtNode);
var elemCheckbox = document.createElement("input");
elemCheckbox.setAttribute("id", 'check'+ elementChiCount);
elemCheckbox.setAttribute("type", 'checkbox');
var divElem = document.createElement("div");
divElem.appendChild(elemNode);
divElem.appendChild(elemCheckbox);
divElem.setAttribute("id", "item"+elementChiCount);
divElem.setAttribute("style", "border: 1px solid pink; width: 250px;padding-left:10px");
element.appendChild(divElem);
}
function addList(txtInput) {
creatList(txtInput);
}
function deleteList() {
elementChiCount = element.getElementsByTagName("div").length;
for (var i = 0; i < elementChiCount; i++) {
var elementCurr = element.getElementsByTagName("div")[i];
if(elementCurr.getElementsByTagName("input")[0].checked == true){
var thisElem = elementCurr.parentNode;
thisElem.removeChild(elementCurr);
break;
} else {
} }
}
return {
add: addList,
del: deleteList
}
})();
</script>
<script type="text/javascript">
var actBtn = document.getElementById("bt1");
var delBtn = document.getElementById("bt2");
actBtn.onclick = function() {
var txtVaue = document.getElementById("txt1").value;
Todo.Item.add(txtVaue);
}
delBtn.onclick = function() {
Todo.Item.del();
}
</script>
</body>
</html>
This is an answer to your question regarding how to keep your lists until you want to remove them.
Why don't you take a look at window.localstorage to allow your lists to persist on refresh.
The following code uses the localStorage and JSON libraries.
The JSON library converts your listData json object into a string in order to store it (localStorage only stores strings), and then after retrieving that string, converting it back into a json object for you to use in your script.
// to save the list
var listDataAsString = JSON.stringify(listData);
localStorage.setItem('list_' + listId, listDataAsString);
// to get the list
var listDataAsString = localStorage.getItem('list_' + listId);
var listData = JSON.parse(listDataAsString);
// to remove the list
localStorage.removeItem('list_' + listId);
Personally I use the localforage library from mozilla, but then you need to look at promises or callbacks. This simplest is to use callbacks.
// to save the list
localforage.setItem('list_' + listId, listData, function (err, listData) {
console.log('Saved list', listId, listData);
});
// to get the list
localforage.getItem('list_' + listId, function (err, listData) {
console.log('Retrieved list', listId, listData);
});
// to remove the list
localforage.removeItem('list_' + listId, function (err, listData) {
console.log('Removed list', listId, listData);
});
Even with the simple use case you seem to have, I would use localforage as it will handle choosing the best storage and any object to string conversion that may need to be carried out.
Related
Update: I got it to work
I have the following code:
function saveLocal() {
var a = prompt("Name:");
document.getElementById("variables").innerHTML += a + ", ";
var p = document.getElementById("variables").value;
localStorage.setItem("names", p);
}
function retrieve() {
var d = localStorage.getItem("names");
document.getElementById("variables").value = d
}
#variables {
color: lime;
font-size: 1.25rem;
border: 0px;
width: 100%;
outline: none;
resize: none;
text-align: center;
}
<button onclick="saveLocal()">Save</button>
<br>
<textarea id="variables" readonly>Saved Names are: </textarea>
<button onclick="retrieve()">Retrieve Note Names</button>
This will prompt for a name and then add it to the textarea while saving it to a localStorage. However, after I push the retrieve button, I cannot add more variables. Or at least doesn't show. How do I fix this?
You can use JSON parse/stringify to store an array of names.
function getNames(){
names = localStorage.getItem("names") || "[]"
return JSON.parse(names);
}
function saveLocal() {
names = getNames()
var a = prompt("Name:");
if (a) {
names.push(a)
localStorage.setItem("names", JSON.stringify(names))
retrieve()
}
}
function retrieve() {
names = getNames();
document.getElementById("variables").value = "Saved Names are: " + names
}
retrieve()
<button onclick="saveLocal()">Save</button>
<br>
<textarea id="variables" readonly></textarea>
<button onclick="retrieve()">Retrieve Note Names</button>
on your saveLocal() function, you could do this:
function saveLocal() {
var currentNames = localStorage.getItem('names')
var updatedNames = currentNames + ', ' + a)
localStorage.setItem('names', updatedNames)
}
this will get the names already stored (variable currentNames) and will concatenate with the new name (your a). Then you just need to store the new names with localStorage.setItem.
<!DOCTYPE html> <!--Declare the document type and version of HTML-->
<html>
<head><!--Information related to the decument-->
<title>Task List</title>
<link rel="stylesheet" href="mydesign.css">
</head>
<body><!--Information related to display the decument-->
[<img src="cm1XiuT.png" alt="CounterStrike" style="width:100%;height:250pt;">][1]
<input type="text" placeholder="Add Tasks Here..." id="taskValue">
<button id="addBtn" onclick="addTask()">add</button>
<!--horizontal Rule-->
<hr>
<section id="content">
</section>
<script>
/creates an Array variable tasks checks if there are any stored
tasks in the browser Conditional statement - Checks IF there is
data stored then imports the data to the array IF not - exitx the
function with an empty array IF THERE IS - exits the function with
the poplulated array/
this is a code
function creatArray()
{
var taskArray = [];
var tasks = localStorage.getItem("itemList");
if(tasks != null)
{
/*code runs if the condition is met*/
taskArray = JSON.parse(tasks);
}
return taskArray;
}
/*Addsa task to the list Creates an array Creates a variable to
store the information in the input fieldset clears the information
in the input field Pushes the task into our Array Stores the
updated Tasklist in the browser Calls the displayTask Function
*/
function addTask()
{
var taskList = creatArray();
var task = document.getElementById("taskValue").value;
document.getElementById("taskValue").value = "";
taskList.push(task);
localStorage.setItem("itemList",JSON.stringify(taskList));
displayTask();
}
/*Removes a task from the list creats a variable to store the
correct button information. this - as in "this"button that has been
clicked creats an array removes the task from our array and
defines how many items we need to remove calls the displayTask
function */
function removeTask()
{
//remove the tasks from the array
var rID = this.getAttribute("id");
var taskList = createArray();
taskList.splice(rID, 1);
localStorage.setItem("itemList",JSON,stringify(taskList));
displayTask();
}
/*displays Tasks in the list Creates the array of tasks creates
the variable to store the list items LOOP statement - adds HTML to
each list item in the array {repeats until the end of the }
replaces the content in the section tag with id="content"
creates a button array LOOP STATMENT - adds an EvenListenerr to
each button in the List */
function displayTask()
{
var taskList = createArray();
var showTasks = "<ul>";
for(var i=0; i < taskLIst.length; i++)
{
showTasks += "<li>"+taskList[i]="<button class='rmvBtn'id='"+i+"'>remove</button></li>"
}
showTasks += "</ul>";
document.getElementById("content"),innerHTML =showTasks;
var btnArray = document.getElementById("rmvBtn");
for(i =0; i < btnArray.length; 1++)
{
btnArray[i].addEventListener('click',removeTask);
}
}
displayTask()
</script><!--includes an external javascript file-->
</body>
</html>
Look, only javascript and html
HTML
<div id="tasks"></div>
<div>
<input type="text" id="newTaskInput">
<button onclick="add()">Add</button>
</div>
JavaScript
var tasks = []
function init() {
tasks = load()
renderTasks()
}
init()
function renderTasks() {
var container = document.getElementById('tasks')
var frag = document.createDocumentFragment()
tasks.forEach(function(item, i) {
var div = document.createElement('div')
var text = document.createTextNode(item.name)
div.appendChild(text)
var closeBtn = document.createElement('button')
var btnText = document.createTextNode('x')
closeBtn.appendChild(btnText)
closeBtn.onclick = function() {
remove(i)
}
div.appendChild(closeBtn)
frag.appendChild(div)
})
container.innerHTML = ""
container.appendChild(frag)
}
function add() {
var input = document.getElementById('newTaskInput')
tasks.push({ name: input.value })
renderTasks()
save(tasks)
}
function remove(index) {
tasks.splice(index, 1)
renderTasks()
save(tasks)
}
function save(data) {
localStorage.setItem('tasks', JSON.stringify(data))
}
function load() {
var raw = localStorage.getItem('tasks')
if ( raw ) {
return JSON.parse(raw)
}
return []
}
DEMO
I really need some help to create this order list. It's the mening that, when you click on the button it adds the text inside the addToList, to the div, so it shows up on the page. It should add the data (name, price), in javascript.
But can't get it to work properly.
<html>
<body>
<div id="myList">
</div>
<button onclick="addToList('donut', '25,-')">add</button>
</body>
</html>
<style>
#myList {
border: 1px solid black;
margin-bottom: 10px;
}
</style>
<script>
function displayListCart() {
var myList = document.getElementById("myList");
};
function addToList(name,price) {
var itemOrder = {};
//itemOrder with data
itemOrder.Name=name;
itemOrder.Price=price;
//Add newly created product to our shopping cart
listCart.push(itemOrder);
displayListCart();
}
</script>
Here is a Fiddle Demo.
I'm not a fan of inline calls to JavaScript functions because it violates separation of concerns, so I've changed the way the event is bound. This isn't part of your problem, but I'm using this approach:
HTML:
<div id="myList">
</div>
<button id="btn" data-name="donut" data-price="25,-">add</button>
Note:
I've added the values as data attributes on the button. You can then
access them from JavaScript.
JavaScript:
function displayListCart(listCart) {
var myList = document.getElementById("myList");
for (i = 0; i < listCart.length; i++) {
myList.innerHTML = myList.innerHTML + listCart[i].Name + " : " + listCart[i].Price;
}
};
function addToList(name, price) {
var itemOrder = {};
//itemOrder with data
itemOrder.Name = name;
//debugging -- check to make sure this returns what you expect
console.log(itemOrder.Name);
itemOrder.Price = price;
//debugging -- check to make sure this returns what you expect
console.log(itemOrder.Price);
//Add newly created product to our shopping cart
//declare listCart before you use it
var listCart = [];
listCart.push(itemOrder);
//pass listCart to the display function
displayListCart(listCart);
}
function getValues() {
addToList(myBtn.getAttribute('data-name'), myBtn.getAttribute('data-price'));
}
var myBtn = document.getElementById("btn");
myBtn.addEventListener("click", getValues, false);
Notes:
You need to declare listCart before you add objects to it.
I suspect you intended to pass listCart to the display function so that you can access the objects within it for display.
You were missing the logic that adds the values to the div. You need to iterate over the array and access the object properties.
First of all, if you open the Dev Tools, you will see an error - Uncaught ReferenceError: listCart is not defined. So the first thing you need to do is create listCart array, like this : var listCart = [];
Then you should modify your displayListCart function, to display a new div for every item in listCart, like this:
function displayListCart() {
var myList = document.getElementById("myList"),
myListContent = "";
listCart.forEach(function(cart) {
myListContent += "<div>" + cart.Name + ": " + cart.Price + "<div>";
});
myList.innerHTML = myListContent;
};
The code example
i have two files
1)index.php
and
2)code.js
now code in index.php is below
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<link href="http://web.guru99.com/lib/codemirror.css" rel="stylesheet" />
<script type="text/javascript" src="code.js"></script>
<style type="text/css">
.CodeMirror {
border: 1px solid #eee;
height: auto;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
</head>
<body>
Integer : whole numbers e.g. -3, 0, 69. The maximum value of an integer is platform-dependent. On a 32 bit machine, its usually around 2 billion. 64 bit machines usually have larger values. The constant PHP_INT_MAX is used to determine the maximum value.
<pre class="codeguru">say 'hi';</pre>
Let us now look at how PHP determines the data type depending on the attributes of the supplied data.
<pre class="codeguru">say 'hello';</pre>
Floating point numbers
<pre class="codeguru">say 'you r amazing';</pre>
Character strings
<pre class="codeguru">say 'i am fine';</pre>
</div>
<form class="hidden code-box" method="GET" name="sample">
<div dir="ltr"><textarea class="php" name="codeguru"></textarea></div>
<input type="submit" value="Run" onclick="execute();"/>
</br></br>
Output:</br></br>
<textarea id="print-result" disabled="true" cols="77"></textarea></br>
</form></div>
</body>
</html>
and code.js file contain code is given below
$(document).ready(function()
{
$('pre.codeguru').each(function()
{
var pre = this;
var form = $('form[name=sample]').clone();
$(form).removeAttr('name');
$(form).removeClass('hidden');
$($(form).find('textarea')[0]).val($(pre).text());
var id = $(pre).attr('id');
$(form).find('div textarea[name=code]').first().attr('id', id);
$(pre).replaceWith(form);
});
window.editors = [];
$('textarea[name=codeguru]').each(function()
{
window.editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
});
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = editor.getValue();
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('print-result').value = "";
try {
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
}
catch(err) {
//document.getElementById('log-result').value += "Error:\n";
}
}
everything is run fine in my code. in code.js pre tags are replaced by textarea and the code in textarea should be run because this project is of online perl editor. so now my problem is i have alert the value of text area by this code
var source = editor.getValue();
alert(source);
but that gives the blank pop up. so what i have to do for retrieve current value of textarea?
You have created more than one editor in this code. These seems to be stored in editors array. Now you want to execute execute() by clicking a button, but you're not telling JS, which editor value you want to alert.
The value of the first editor on the page can be reached like this:
var source = editors[0].getValue();
editor.getValue() is supposed to give you the value of the last editor in the editors array.
Since you have a separate button for each editor, you can pass the editor's index in the editors array to execute() function.
At first, remove the onclick attribute from the button input, then:
After $('pre.codeguru').each();, attach eventlisteners to buttons:
var n = 0;
$('input[type=button]').each(function () {
$(this).click(function (x) {
return function () {
execute(x);
};
}(n++))
}
);
And in the execute():
function execute(idx) {
...
var source = editors[idx].getValue();
alert(source);
....
}
UPDATE
Updated the fiddle code to output to a corresponding field.
And here is an updated live demo.
I am using Javascript to display headers on a SharePoint site, according to a column that I have specified HTML in. Here is the HTML.
<DIV style ='text-align:center; font-weight:bold; font-size: 20px;'>◆</DIV>
The problem is that the script, while rendering the HTML properly within the page, does not do the same for header. It works 90% of the way, but instead of displaying the unicode "◆", it renders "â".
I've already tried modifying the Javascript to try to account for the unicode \u25c6, but I'm failing miserably. Can anyone help me out or provide me some clues as to why this is happening?
Here is the Javascript.
<script type="text/javascript">
// Find all Web Parts in the page
var listWP = [],
calWP = [],
divs = document.getElementById("MSO_ContentTable").getElementsByTagName("div");
var count=divs.length;
for (i=0;i<count;i++) {
try {
if (divs[i].id.indexOf("WebPartWPQ")==0){
if (divs[i].innerHTML.indexOf("ViewDefault_CalendarView")>=0) {
// Calendars
calWP.push(divs[i].id);
} else {
// Other Web Parts
listWP.push(divs[i].id);
}
}
}
catch(e){}
}
function TextToHTML(NodeSet, HTMLregexp) {
var CellContent = "";
var i=0;
while (i < NodeSet.length){
try {
CellContent = NodeSet[i].innerText || NodeSet[i].textContent;
if (HTMLregexp.test(CellContent)) {
NodeSet[i].innerHTML = CellContent;
}
}
catch(err){}
i=i+1;
}
}
var regexpA = new RegExp("\\s*<([a-zA-Z]*)(.|\\s)*/\\1?>\\s*$");
var regexpTD = new RegExp("^\\s*<([a-zA-Z]*)(.|\\s)*/\\1?>\\s*$");
var WP = new Object;
function UpdateWP() {
if (calWP.length>0){
for (i=0;i<calWP.length;i++) {
WP=document.getElementById(calWP[i]);
if (WP.innerHTML.indexOf("<\;")>=0) {
TextToHTML(WP.getElementsByTagName ("a"),regexpA);
}
}
}
if (listWP.length>0){
for (i=0;i<listWP.length;i++) {
WP=document.getElementById(listWP[i]);
if (WP.innerHTML.indexOf("<\;")>=0) {
TextToHTML(WP.getElementsByTagName ("td"),regexpTD);
}
}
}
// Check every 200000000 ms, forever
setTimeout("UpdateWP()",200000000);
}
UpdateWP();
function HeaderToHTML(){
var headers=document.getElementById("MSO_ContentTable").getElementsByTagName("li");
var regexpTR1 = new RegExp("FilterValue1=([\\S\\s]*)'\\)");
var regexpTR2 = new RegExp("FilterValue2=([\\S\\s]*)'\\)");
for (i=0;i<headers.length;i++) {
try{
var sp=headers[i].getElementsByTagName("span");
for (j=0;j<sp.length;j++) {
var test = sp[j].innerText || sp[j].textContent || " ";
//var test = sp[j].innerText;
if (test.indexOf("...")>0) {
//alert(test);
//var value = regexpTR1.exec(headers[i].innerHTML)[1];
var inner = headers[i].innerHTML;
var value = (inner.indexOf("FilterValue2")>0) ? regexpTR2.exec(headers[i].innerHTML) [1] : regexpTR1.exec(headers[i].innerHTML)[1];
//alert(value);
//alert(value.replace(/\\u00/g,"\%"));
value=value.replace(/\\u00/g,"%");
sp[j].innerHTML=unescape(unescape(value)).replace(/8_/," ");
}
}
}catch(e){}
}
}
setInterval(function(){HeaderToHTML();},100);
</script>
I would suggest using the html dex/dec for the symbols.
that is,
◆ = ◆
◆ = ◆
Wikipedia has a nice list of them broken into categories here.
I found the black diamond you're trying to write here
I think a solution could be to render your character in its encoding and let browser know about it via:
<meta http-equiv="Content-Type" content="text/html; charset="...">
For example, if you are using UTF-8:
<meta http-equiv="Content-Type" content="text/html; charset="UTF-8">