I'm trying to create a list which I can edit/update. I'll need to be able to store the list information in a variable of some sort and display the information on a HTML page.
My attempt is in the jsbin below.
JSBIN
https://jsbin.com/luxobineze/edit?html,js,console,output
So with that code, I'd like to:
Add names by filling in the form and clicking "Add Name"
Click [Edit] which will fill the form with the name that is to be edited
Click Update to update the global variable "names" (If I can do this, then I should be able to update the HTML's "List of Names" as well)
I'm not sure what to do in the updateName function since I'm not sure how to pass the relevant arguments into it in order to update the correct list item. Do I need to use more global variables to keep track of the list item that's being edited? Or is there a better, more standard way of coding this?
The code in the jsbin is here:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
Name: <input type="text" id="name-input"><br>
<button id="add-name" class="button">Add Name</button>
<button id="update" class="button">Update</button>
<div id="list">List of Names</div>
</body>
</html>
JavaScript
// global variable storing the list of names
var names = [];
function addName() {
var name = document.getElementById("name-input").value;
var list = document.getElementById("list");
if(name) {
names.push("name");
var wrapper = document.createElement("div")
wrapper.setAttribute("id", name)
var div_name = document.createElement("div");
div_name.appendChild(document.createTextNode(name))
var div_edit = document.createElement("div")
div_edit.appendChild(document.createTextNode("[edit]"))
div_edit.addEventListener("click", editName)
wrapper.appendChild(div_name)
wrapper.appendChild(div_edit)
list.appendChild(wrapper)
}
}
function editName() {
// Fill the input box with the name that you want to edit
var name = this.parentElement.getAttribute("id")
document.getElementById("name-input").value = name;
}
function updateName() {
var new_name = document.getElementById("name-input").value
// How do I update the global variable "names"?
}
document.getElementById("add-name").addEventListener("click", addName)
document.getElementById("update").addEventListener("click", updateName)
Edit
I ended up using some global variables to keep track of which item was currently selected: https://jsbin.com/zupawesifu/1/edit?html,js,console,output
What it sounds like you're doing is building the most basic of applications, a CRUD app. (Create, Read, Update, Delete)
Storing your values in a local variable is not the most desirable way of doing this, unless of course that is your desired functionality.
You ask "is there a more standard way". A more common way would be to store your values in a database, or, in an even simpler scenario, you could store these values in a local .JSON file. This will allow you to use your application at any time, close the application, refresh, or any other number of things without losing your stored or edited values.
I won't code a full CRUD app for you here, but there are many tutorials and templates out there for your learning pleasure. Here is very basic one.
I hope this helps!
http://mrbool.com/creating-a-crud-form-with-html5-local-storage-and-json/26719
Related
I'm Roberto and I'm just a beginner of Javascript. I'm learning on a site and I'm going to get a book of Javascript very soon.
I came across an example: I want to read the elements of the list and tweak the own class of each element( in this case, I want to delete the classes).
As you all can see, for reading all the elements I wrote
var elementi = document.getElementsByTagName('li');
and to verify that everything is gone well I put an alert( elementi[0] ); after the "var elementi..........", then i wrote the rest of the code.
When I open the Window of the browser, It runs a pop-up that contains object HTMLLlElement text.
How can I get rid of this mistake? And what does it mean?
var elementi = document.getElementsByTagName('li');
alert ( elementi[1] );
for ( var i = 0 ; i< elementi.lenght; i++){
elementi[i].className = " ";
}
<!DOCTYPE html>
<HTML>
<head>
<link rel="stylesheet" type="text/css" href="mycss.css">
<title> Javascript </title>
</head>
<body>
<h1><p>Javascript</p></h1>
<p class="subtitle">Shopping list:<p>
<ul id="lista">
<li>Pasta</li>
<li >Crocchette</li>
<li >Lotamma</li>
</ul>
<script type="text/javascript" src="corso01.js"></script>
</body>
</HTML>
You simply need to remove this line:
alert ( elementi[1] );
To no longer get the message. But, the message itself it just showing what type of object you have (element[1] is a list item HTML element). You could modify the alert to be more specific by changing it to:
alert ( elementi[1].textContent);
Which would show "Crocchette" because that is the text that is stored in the list item.
It's coming up because the JavaScript code you've shown is automatically running as soon as the page is loaded. In practice, you'll most likely want to move that code into a function that is called at a particular time, called an event. This could be when the user interacts with the page in some way (a click, a mouseover, etc.).
Also, you should change this:
elementi[i].className = " "
to this:
elementi[i].className = "";
The second one removes the space between the quotes so that instead of setting a class name to an actual space character, you are setting the class name to an empty string (no space).
to remove a class from an element, you want to use the remove method on the classList property, like this:
elementi[i].classList.remove('lined');
I'm developing restaurant management system using MeteorJS. What I try to accomplish here is when I type in some number on "Quantity" column it multiples itself with the price in "Price" column, then displays total sales inside textbox in "Total" column. I'm aware that there're several solutions out there but I wonder if this can be done using Meteor template helpers.
Screenshot
Yes it can, Meteor template is reactive so you simply need to do something like:
<template name="costCalcualtor">
<input id="quantity">
<p id="price">$10</p>
<p>It'd be ${{totalCost}}.</p>
</template>
in your html, and in your JS, simply makes a Template.costCalcualtor event that fires every time user finish typing in the input of "quantity" id, parse the innerHTML as integer, multiply it by the price (another integer obtained by parsing innerHTML of the p of "price" id), Session.set('price',finalValue), then have totalCost as a Template.costCalcualtor helper function that returns a new value based on Session.get("price").
Update:
don't just return a variable in the keyup event, you should use Session.set("total", price*quantity); in the end, and the line var total = parseInt($('total').val(price * quantity)); doesn't really do anything.
then you need {{totalCost}} in the template. and define a helper to retrieve the value of the session variable "total": Session.get("total").
Here is a walk-through to demonstrate what I mean:
in your .js fileh:
if (Meteor.isClient) {
// counter starts at 0
Session.setDefault('counter', 0);
Template.salesAdd.helpers({
total: function(){
return Session.get("total")
}
});
Template.salesAdd.events({ 'keyup #meow': function() {
var quantity = parseInt($('#meow').val());
console.log(quantity);
Session.set("total", quantity); } })
}
in your .html file:
<head>
<title>meow</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> salesAdd}}
</body>
<template name="salesAdd">
<input id="meow">
<p> What you've typed: {{total}}</p>
</template>
run it & see the number changes as you type in <input>.
Meteor is very a powerful tool developed by great people, and what is nice about it is that it is easy-to-learn and it has good documentation, so I suggest you to go through the basic docs and if possible, the full api.
I am experimenting with XForms and trying to dynamically load javascript, but cannot figure it out.
I am presenting a simple example - that is just an input field and button that loads the javascript:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xf="http://www.w3.org/2002/xforms"
xmlns:ev="http://www.w3.org/2001/xml-events" >
<head>
<title>Hello World in XForms</title>
<xf:model>
<xf:instance xmlns="">
<data>
<firstName/>
</data>
</xf:instance>
</xf:model>
<script type="text/javascript">
var myFunction = function(){
var name = document.getElementById("firstName").value;
alert("Hello " + name + "!");
}
</script>
</head>
<body>
<xf:label>Please enter your first name: </xf:label>
<xf:input ref="firstName" id="firstName">
</xf:input>
<br />
<xf:trigger>
<xf:label>Click me!</xf:label>
<xf:action ev:event="DOMActivate">
<xf:load resource="javascript:myFunction()" />
</xf:action>
</xf:trigger>
</body>
</html>
So in my script I am trying to get the value from the input box and then show an alert box with concatenated string. Currently, I get "Hello undefined!"
Do you have an idea how to get the value from the firstName xf:input with Javascript?
I know how to do it with XForms only, but this is sort of a proof of concept.
On a side note - I am using XSLTForms, so the XForms runs on the client.
Another hint might be in the fact that XSLTForms transforms the xf:input into several nested span elements with a <input type="text"> element, but that input element does not have a name or id.
With XSLTForms, there are different possibilities...
If you want to access the value of the corresponding HTML input, I would suggest document.getElementById("firstName").xfElement.input.value.
You could also use the node property to get the value stored in the bound node.
Don't hesitate to browse DOM with a debugger to find how to get things from XSLTForms!
--Alain
I am trying to practice javascript and I read a small challenge on a website about making a small system where users can follow and unfollow one another. I am still new to javascript and programming in general so please forgive my ignorance. Below is what i came up with. I am trying to make this off the top of my head because this might be the best way to learn a language imo.
Basically in this small function, I created an empty array set in a function. I then set the function to the onClick handler in the tag. Is this a good way to store names or things in general? Am I on the right track to do this small task?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="searchbox" value = "names">
<button type="radio" onClick="listOfPeople();">
<script type="text/javascript">
"use strict";
function listOfPeople (){
var storedPeople = [];
listOfPeople();
};
</script>
</body>
</html>
Since you've declared the storedPeople array inside the listOfPeople function, that will limit the "scope" from where you can add or remove items from it to the listOfPeople function.
Something like this would not work with your setup currently, because the storedPeople array is is in a "closure" because it was declared inside a function.
<script type="text/javascript">
function listOfPeople (){
var storedPeople = [];
listOfPeople();
};
alert(storedPeople[0]);
</script>
This should show how to declare the array outside of the function so it has a "wider scope", meaning that it can be accessed by more than just inside of the listOfPeople function.
<!DOCTYPE html>
<html>
<body>
<input id="searchbox" value = "names">
<button type="radio" onClick="listOfPeople();">
<script type="text/javascript">
// declare the storedPeople array outside of the function
var storedPeople = [];
// modify the array in the function
function listOfPeople (){
storedPeople.push(document.getElementById("searchbox").value);
};
</script>
</body>
</html>
You're properly calling your button.
But there's one problem within your javascript function : inside of 'listOfPeople' you're calling 'listOfPeople'.
You shouldn't do this because it will never stop calling the same function again and again. And then stack overflow : Maximum call stack size exceeded.
Your function should look like :
function listOfPeople (){
var storedPeople = [];
};
Otherwise it is a good start!
you have not clearly mentioned what you need your given code to do.
like others mentioned, listofpeople() is recusrive but there's no condition to break it.
try to create your code in http://plnkr.co/ and explain what is it that you want as opposed to what is happening.
in case you want to do the search progressively as the user types you may use 'onchange' see the demo here http://www.w3schools.com/jsref/event_onchange.asp
as a modification to Zack's code it would be
<body>
<input id="searchbox" value = "names" onchange="listOfPeople();">
<button type="radio" onClick="listOfPeople();">
I am trying to find the best way to merge two HTML String in Javascript (JQuery/AngularJS) such as :
var context = '<html>
<head>
</head>
<body>
<ul id="list">
<li>itemA</li>
<li>itemB</li>
</ul>
</body>
</html>';
merged with :
var additionnalInfo = '<ul id="list">
<li>itemC</li>
<li>itemD</li>
</ul>';
should modify context variable to :
'<html>
<head>
</head>
<body>
<ul id="list">
<li>itemA</li>
<li>itemB</li>
<li>itemC</li>
<li>itemD</li>
</ul>
</body>
</html>';
Any idea ?
Should be able to do something like this, as long as your additional info contains only the elements you want to add (which you can easily strip down to).
var additionnalInfo = '<li>itemC</li>
<li>itemD</li>';
var list = getElementById('list');
list.innerHTML += additionalInfo;
Edit
If you must be able to match on several ids, then its possible you could use jQuery to iterate through all elements of a type (all lists for example), and just check the ids for equality, then append as above. Ex:
var additionalInfo = $.parseHTML('<ul id="list"><li>itemC</li><li>itemD</li></ul>');
var elements = additionalInfo.find($('ul'));
var lists = $('ul').get();
elements.each(function(){
var el = this;
lists.each(function(){
if($(this).attr('id') == el.attr('id')){
el.innerHTML += $(this).innerHTML;
}
});
There are more efficient ways of doing this, but it should be a good basis for what you need. Essentially just loop through all of the "parent" list elements in the additional html. Compare those ids against the list ids within your existing html, and if they are the same, then append the new innerHTML to the existing list.
You can also make it more generic so that once you parse your html string, get the type of any element with an id, and do a find for that type. A lot of ways to do this, its just a matter of applying the proper method of iterating through your data without wasting a ton of cycles. Hope this helps a bit more.