Delete row dynamically in JavaScript - javascript

I'm doing a form (a simple WEB form, based on the scripts from Tom Negrino, JavaScript 8, and w3Schools) where the user press the Submit button and some of the fields from the form are displayed in one table under the form.
This is the result
Form
Now, I want to delete the row , but only the row that the user wants to delete clicking on the corresponding row.
This is my JavaScript
window.onload = initForms;
function initForms() {
for (var i=0; i< document.forms.length; i++) {
document.forms[i].onsubmit = validForm;
}
document.getElementById("sunroof").onclick = doorSet;
document.getElementById("estado").selectedIndex = 0;
document.getElementById("estado").onchange = populateDays;
/***********/
//document.getElementsByTagName("form")[0].onsubmit = addNode;
/***********/
document.getElementById("env").onclick = function() {
myFunction()
};
}
function validForm() {
var allGood = true;
var allTags = document.getElementsByTagName("*");
for (var i=0; i<allTags.length; i++) {
if (!validTag(allTags[i])) {
allGood = false;
}
}
return allGood;
function validTag(thisTag) {
var outClass = "";
var allClasses = thisTag.className.split(" ");
for (var j=0; j<allClasses.length; j++) {
outClass += validBasedOnClass(allClasses[j]) + " ";
}
thisTag.className = outClass;
if (outClass.indexOf("invalid") > -1) {
invalidLabel(thisTag.parentNode);
thisTag.focus();
if (thisTag.nodeName == "INPUT") {
thisTag.select();
}
return false;
}
return true;
function validBasedOnClass(thisClass) {
var classBack = "";
switch(thisClass) {
case "":
case "invalid":
break;
case "reqd":
if (allGood && thisTag.value == "") {
classBack = "invalid ";
}
classBack += thisClass;
break;
case "radio":
if (allGood && !radioPicked(thisTag.name)) {
classBack = "invalid ";
}
classBack += thisClass;
break;
case "email":
if (allGood && !validEmail(thisTag.value)) classBack = "invalid ";
break;
case "isNum":
case "isZip":
classBack += thisClass;
break;
default:
if (allGood && !crossCheck(thisTag,thisClass)) {
classBack = "invalid ";
}
classBack += thisClass;
}
return classBack;
}
function crossCheck(inTag,otherFieldID) {
if (!document.getElementById(otherFieldID)) {
return false;
}
return (inTag.value != "" || document.getElementById(otherFieldID).value != "");
}
function validEmail(email) {
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return re.test(email);
}
function radioPicked(radioName) {
var radioSet = "";
for (var k=0; k<document.forms.length; k++) {
if (!radioSet) {
radioSet = document.forms[k][radioName];
}
}
if (!radioSet) {
return false;
}
for (k=0; k<radioSet.length; k++) {
if (radioSet[k].checked) {
return true;
}
}
return false;
}
/****Veamos si esto funciona****/
/*function checkboxPicked(checkboxName) {
var checkboxSet = "";
for (var k = 0; k < document.forms.length; k++) {
if (!checkboxSet) {
checkboxSet = document.forms[k][checkboxName];
}
}
if (!checkboxSet) {
return false;
}
for ( k = 0; k < checkboxSet.length; k++) {
if (checkboxSet[k].checked) {
return true;
}
}
return false;
}*/
/*****************************************/
function invalidLabel(parentTag) {
if (parentTag.nodeName == "LABEL") {
parentTag.className += " invalid";
}
}
}
}
function populateDays() {
var tamps = new Array("Ikon Hatch", "Fiesta", "Focus", "Mustang");
var nvoleon = new Array("Aveo", "Spark");
var slp = new Array("Gol", "CrossFox", "Clasico", "Jetta");
var estado = document.getElementById("estado");
var estadoStr = estado.options[estado.selectedIndex].value;
if (estadoStr != "") {
var valueEst = parseInt(estadoStr);
document.getElementById("ciudad").options.length = 0;
if (valueEst == 0) {
for (var i = 0; i < tamps.length; i++) {
document.getElementById("ciudad").options[i] = new Option(tamps[i]);
}
} else if (valueEst == 1) {
for (var i = 0; i < nvoleon.length; i++) {
document.getElementById("ciudad").options[i] = new Option(nvoleon[i]);
}
} else if (valueEst == 2) {
for (var i = 0; i < slp.length; i++) {
document.getElementById("ciudad").options[i] = new Option(slp[i]);
}
}
} else {
document.getElementById("ciudad").options.length = 0;
document.getElementById("ciudad").options[0] = new Option("Model");
}
}
function doorSet() {
if (this.checked) {
document.getElementById("twoDoor").checked = true;
}
}
/*****************************/
/*function addNode() {
var inText = document.getElementById("estado").value;
var inText1 = document.getElementById("ciudad").value;
var newText = document.createTextNode(inText);
var newText1 = document.createTextNode(inText1);
var newGraf = document.createElement("table");
newGraf.appendChild(newText);
newGraf.appendChild(newText1);
var docBody = document.getElementsByTagName("body")[0];
docBody.appendChild(newGraf);
return false;
}*/
function myFunction() {
var table = document.getElementById("myTable");
var email= document.getElementById("emailAddr").value;
var brand=document.getElementById("estado").value;
var model=document.getElementById("ciudad").value;
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = email;
cell2.innerHTML = model;
cell3.innerHTML = brand;
}
And my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Formulario</title>
<link rel="stylesheet" href="css/script06.css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap-theme.min.css">
<!--No se te olvide el css-->
<!--<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap-theme.min.css">-->
<script src="js/script08.js"></script>
<!--No se te olvide el js-->
</head>
<body>
<header></header>
<main>
<article>
<p>
<h1>Choose your car</h1>
</p>
</article>
<form action="#">
<p>
<label for="emailAddr">Email Address:
<input id="emailAddr" type="text" size="40" class="reqd email">
</label>
</p>
<p>
<label for="passwd1">Password:
<input type="password" id="passwd1" class="reqd">
</label>
</p>
<p>
<label for="passwd2">Repeat Pass:
<input type="password" id="passwd2" class="reqd passwd1">
</label>
</p>
<!--<p>
<label for="color">Colors:
<select id="color" class="reqd">
<option value="" selected>Choose a color</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select> </label>
</p>-->
<p>
Options: <label for="sunroof">
<input type="checkbox" id="sunroof" value="Yes">
Sunroof (Two door only)</label>
<label for="pWindows">
<input type="checkbox" id="pWindows" value="Yes">
Power Windows</label>
</p>
<p>
Doors: <label for="DoorCt"><!--Doors: -->
<input type="radio" id="twoDoor" name="DoorCt" value="twoDoor" class="radio">
Two</label>
<label for="DoorCt">
<input type="radio" id="fourDoor" name="DoorCt" value="fourDoor" class="radio">
Four </label>
</p>
<p>
<label>Brand:</label>
<select id="estado" class="reqd">
<option value="">Brand</option>
<option value="0">Ford</option>
<option value="1">Chevrolet</option>
<option value="2">Volkswagen</option>
</select>
<select id="ciudad" class="reqd">
<option>Model</option>
</select>
</p>
<p>
<input type="submit" value="Enviar" id="env">
<input type="reset">
</p>
</form>
<br />
<!--Veamos si funciona-->
<table id="myTable">
<tr>
<td>Email</td>
<td>Model</td>
<td>ID Brand</td>
</tr>
<tr>
</tr>
</table>
</main>
<footer></footer>
</body>
</html>
I tried adding and extra cell in the JavaScript:
cell4.innerHTML = <button onclick="myDeleteFunction()">Del</button>;
where calls the function
function myDeleteFunction() {
document.getElementById("myTable").deleteRow();
}
to delete to row, but it didn't work.
I'll appreciate any help. Thanks.

var node = nodes[0];
if (univArray[z].ownership != "public") {
node.parentNode.removeChild(node)
}

If you want to delete a table row based on a click on the row, you can use something like:
<tr onclick="this.parentNode.removeChild(this)">
If you want to do that based on a button in the row, then:
<tr>
<td><button onclick="deleteRow(this)">Delete this row</button>
Then the deleteRow function is:
function deleteRow(element) {
var row = upTo(element, 'tr');
if (row) row.parentNode.removeChild(row);
}
A helper function
// Return first ancestor of el with tagName
// or undefined if not found
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
// Many DOM methods return null if they don't
// find the element they are searching for
// It would be OK to omit the following and just
// return undefined
return null;
}
The deleteRow function can be put anywhere inside a row, and the row can be in any type of table section element (head, body or foot). All you need to do is to pass a reference to any element inside the row (button, checkbox, cell, whatever).
The trouble with the table.deleteRow method is that you have to know the row index in the element that you're calling the method on. Rows have a rowIndex property that is their index in the table they are in, so you have to go up to the table to use that (i.e. row.parentNode.parentNode), whereas using the removeChild method doesn't require you to work out where in the table the row is, or to even know whether the parent is a head, body or foot section.
Edit
To add the listener dynamically, you can slightly modify the function and add a class to the buttons that will delete rows, e.g.
<!-- Sample markup -->
<table>
<tr>
<td><input type="button" class="rowDeleter" value="Delete Row">
<tr>
<td><input type="button" class="rowDeleter" value="Delete Row">
<tr>
<td><input type="button" class="rowDeleter" value="Delete Row">
</table>
Adding a class means you can easily identify the elements to add the listener to.
<script>
window.onload = function() {
// querySelectorAll and addEventListener require IE 8 or higher, use some other
// method if support for older browsers is required
var els = document.querySelectorAll('.rowDeleter');
for (var i=0, iLen=els.length; i<iLen; i++) {
els[i].addEventListener('click', deleteRow, false);
}
}
// When attached using addEventListener, this in the function
// will be the element that called the listener
function deleteRow() {
var row = upTo(this, 'tr');
if (row) row.parentNode.removeChild(row);
}
// Previously shown helper
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
return null;
}
</script>

Related

Generated row of table event listener not working instantly

I have a table like this :
I have added an event listener assetTableEvent() to each text box in the table. My issue is when I add new row to the table, i also add the corresponding event listener to it assetTableEvent(), but the total value does not pop while entering value, it shows only when next row has values entered.
function assetTableEvent() {
let total = 0;
for (var k = 0; k < document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
I even tried calling assetTableEvent() every time there is a change, but it just does not work. Can somebody help me in Javascript how to make dynamically added rows correspond to event listener like above rows.
HTML for Asset table:
<div id="calcContainer">
<div id = "headingText" >
Child Maintenance Calculator
</div>
<div id="startPage">
<button id="startBtn">Start</button>
</div>
<div id="asset">
<table id="assetTable">
<tr>
<th>Asset</th>
<th>Value</th>
<th>Own</th>
<th>Total</th>
</tr>
</table>
<div id="totalAssetsDiv">
<Label for ="totalAssets">Total Assets</Label>
<input type="number" id = "totalAssets" readonly="true">
<br>
</div>
<div id ="rowOps">
<br> <button id="addRow" class = "addDel">Add Row</button>
<button id="removeRow" class = "addDel1">Delete Row</button><br>
</div>
</div>
And add row event listener :
document.getElementById("addRow").addEventListener("click", function () {
var table = document.getElementById("assetTable");
var row = table.insertRow();
for (let j = 0; j < 4; j++) {
var tb = document.createElement("INPUT");
var value = "", idNum = "";
if (j == 0) {
tb.setAttribute("type", "text");
tb.value = value;
}
else {
tb.setAttribute("type", "number");
}
//Setting textbox id
switch (j) {
case 0:
idNum = "a";
break;
case 1:
idNum = "v";
break;
case 2:
idNum = "o";
break;
case 3:
idNum = "t";
break;
}
tb.id = idNum + (table.rows.length);
if (tb.id.includes('t')) {
tb.setAttribute("readOnly", "true");
}
tb.classList.add("assetTBox");
let cell = row.insertCell(j);
tb.addEventListener("input", assetTableEvent, false);
cell.appendChild(tb);
}
});
Trying to use incremental IDs is more work than it is worth, especially when you start removing rows.
I suggest you use classes instead and delegate the event listener to the table itself. When an input event occurs you get the closest row and query for the elements within that row for the row total, then query all of the rows totals for the master total
Basic example with functional add row
const table = document.querySelector('#myTable'),
cloneRow = table.rows[0].cloneNode(true);
table.addEventListener('input',(e) => {
if (e.target.matches('.qty, .price')) {
const row = e.target.closest('tr'),
price = row.querySelector('.price').valueAsNumber || 0,
qty = row.querySelector('.qty').valueAsNumber || 0;
row.querySelector('.amt').value = qty * price;
setTotalAmt()
}
});
document.querySelector('#add-row').addEventListener('click', (e) => {
table.appendChild(cloneRow.cloneNode(true))
});
function setTotalAmt() {
const sum = [...table.querySelectorAll('.amt')].reduce((a, el) => a + (+el.value || 0), 0)
document.querySelector('#total').value = sum;
}
<button id="add-row">
Add Row
</button>
Total:<input id="total" />
<table id="myTable">
<tr>
<td>Qty:
<input type="number" class="qty" value="0" />
</td>
<td>Price:
<input type="number" class="price" value="0" />
</td>
<td>Amt:
<input class="amt" readonly value="0" />
</td>
</tr>
</table>
#charlietfl 's solition is more elegant but if you wonder what is the problem in your code, you should change the < to <= in k < document.getElementById("assetTable").rows.length; part
function assetTableEvent() {
let total = 0;
for (var k = 0; k <= document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
Here is the working example:
document.getElementById("addRow").addEventListener("click", function () {
var table = document.getElementById("assetTable");
var row = table.insertRow();
for (let j = 0; j < 4; j++) {
var tb = document.createElement("INPUT");
var value = "", idNum = "";
if (j == 0) {
tb.setAttribute("type", "text");
tb.value = value;
}
else {
tb.setAttribute("type", "number");
}
//Setting textbox id
switch (j) {
case 0:
idNum = "a";
break;
case 1:
idNum = "v";
break;
case 2:
idNum = "o";
break;
case 3:
idNum = "t";
break;
}
tb.id = idNum + (table.rows.length);
if (tb.id.includes('t')) {
tb.setAttribute("readOnly", "true");
}
tb.classList.add("assetTBox");
let cell = row.insertCell(j);
tb.addEventListener("input", assetTableEvent, false);
cell.appendChild(tb);
}
});
function assetTableEvent() {
let total = 0;
for (var k = 0; k <= document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
<div id="calcContainer">
<div id = "headingText" >
Child Maintenance Calculator
</div>
<div id="startPage">
<button id="startBtn">Start</button>
</div>
<div id="asset">
<table id="assetTable">
<tr>
<th>Asset</th>
<th>Value</th>
<th>Own</th>
<th>Total</th>
</tr>
</table>
<div id="totalAssetsDiv">
<Label for ="totalAssets">Total Assets</Label>
<input type="number" id = "totalAssets" readonly="true">
<br>
</div>
<div id ="rowOps">
<br> <button id="addRow" class = "addDel">Add Row</button>
<button id="removeRow" class = "addDel1">Delete Row</button><br>
</div>
</div>

Unable to retain the table values after refreshing the browser window

Created a form using html, javascript. After entering the fields, when i click submit button, it saves the user data in localstorage and updates the table rows dynamically. But once i refresh the browser, the table holding the information of all users is lost. I want to retain the table after refreshing the browser.
Click here to view screenshot of page Before refresh
Click here to view screenshot of page After refresh
JS Code :
var testObject = [];
var users = {};
function clear(){
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username,usermail,password,location,organization,gender){
if(username!="" && usermail!="" && password!="" && location!="" && organization!="" && gender!=""){
return true;
}
}
function removeDivChild(str)
{
if(document.getElementById(str).querySelector('p')){
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val,cdiv)
{
if(val=="" && document.getElementById(cdiv).querySelector('p')==null)
{
var node = document.createElement("P");
if(document.getElementById(cdiv).className=="textbox"){
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
}
else if(document.getElementById(cdiv).className=="radiobox"){
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if(val!="" && document.getElementById(cdiv).querySelector('p')!=null)
{
document.getElementById(cdiv).lastElementChild.remove();
}
}
function save(){
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if(document.getElementById("m").checked){
genval = document.getElementById("m").value;
}
if(document.getElementById("f").checked)
{
genval = document.getElementById("f").value;
}
if(IsValid(userval,eval,passval,locval,orgval,genval))
{
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
updateTable();
}
else
{
appendToDiv(userval,"userdiv");
appendToDiv(eval,"maildiv");
appendToDiv(passval,"passdiv");
appendToDiv(locval,"locdiv");
appendToDiv(orgval,"orgdiv");
appendToDiv(genval,"gendiv");
}
}
function updateTable(){
localStorage.setItem("user", JSON.stringify(testObject));
var usr = JSON.parse(localStorage.getItem('user'));
var i = testObject.length-1;
if(i==0){
var nodeh = document.createElement("tr");
var usernode = document.createElement("th");
var usertext = document.createTextNode("Username");
usernode.appendChild(usertext);
nodeh.appendChild(usernode);
var enode = document.createElement("th");
var etext = document.createTextNode("Email");
enode.appendChild(etext);
nodeh.appendChild(enode);
var pnode = document.createElement("th");
var ptext = document.createTextNode("Password");
pnode.appendChild(ptext);
nodeh.appendChild(pnode);
var lnode = document.createElement("th");
var ltext = document.createTextNode("Location");
lnode.appendChild(ltext);
nodeh.appendChild(lnode);
var onode = document.createElement("th");
var otext = document.createTextNode("Organization");
onode.appendChild(otext);
nodeh.appendChild(onode);
var gnode = document.createElement("th");
var gtext = document.createTextNode("gender");
gnode.appendChild(gtext);
nodeh.appendChild(gnode);
document.getElementById("t").appendChild(nodeh);
}
var noder = document.createElement("tr");
var nodeu = document.createElement("td");
var textu = document.createTextNode(usr[i].uname);
nodeu.appendChild(textu);
noder.appendChild(nodeu);
var nodee = document.createElement("td");
var texte = document.createTextNode(usr[i].email);
nodee.appendChild(texte);
noder.appendChild(nodee);
var nodep = document.createElement("td");
var textp = document.createTextNode(usr[i].pass);
nodep.appendChild(textp);
noder.appendChild(nodep);
var nodel = document.createElement("td");
var textl = document.createTextNode(usr[i].loc);
nodel.appendChild(textl);
noder.appendChild(nodel);
var nodeo = document.createElement("td");
var texto = document.createTextNode(usr[i].org);
nodeo.appendChild(texto);
noder.appendChild(nodeo);
var nodeg = document.createElement("td");
var textg = document.createTextNode(usr[i].gender);
nodeg.appendChild(textg);
noder.appendChild(nodeg);
document.getElementById("t").appendChild(noder);
clear();
}
HTML code :
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
</head>
<body>
<script src="check.js"></script>
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male"/> Male
<input type="radio" name="gender" id="f" value="female"/> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<table id="t" border="1">
</table>
</body>
</html>
After the back and forth in the comments on your question I decided to just create an example from your code sample. Most of it was untouched however I did add comments to the things that I did change.
// I moved the declaration of the testObject below to let the functions be created first
// so i can use teh new loadFromStorage function to create the object
var users = {};
// This is a new function I created
function loadFromStorage() {
// parse the 'user' object in local storage, if its empty return an empty array
return JSON.parse(localStorage.getItem('user')) || [];
}
function clear() {
// I didn't touch this function
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username, usermail, password, location, organization, gender) {
// I didn't touch this function
if (username != "" && usermail != "" && password != "" && location != "" && organization != "" && gender != "") {
return true;
}
}
function removeDivChild(str) {
// I didn't touch this function
if (document.getElementById(str).querySelector('p')) {
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val, cdiv) {
// I didn't touch this function
if (val == "" && document.getElementById(cdiv).querySelector('p') == null) {
var node = document.createElement("P");
if (document.getElementById(cdiv).className == "textbox") {
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
} else if (document.getElementById(cdiv).className == "radiobox") {
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if (val != "" && document.getElementById(cdiv).querySelector('p') != null) {
document.getElementById(cdiv).lastElementChild.remove();
}
}
// Changes in this function
function save() {
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if (document.getElementById("m").checked) {
genval = document.getElementById("m").value;
}
if (document.getElementById("f").checked) {
genval = document.getElementById("f").value;
}
if (IsValid(userval, eval, passval, locval, orgval, genval)) {
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
// Saving testObject to the persistent storage here because this is where it belongs
localStorage.setItem("user", JSON.stringify(testObject));
updateTable();
} else {
appendToDiv(userval, "userdiv");
appendToDiv(eval, "maildiv");
appendToDiv(passval, "passdiv");
appendToDiv(locval, "locdiv");
appendToDiv(orgval, "orgdiv");
appendToDiv(genval, "gendiv");
}
}
// Changes in this function
function updateTable() {
// pulled out the saving and the loading of user from localStorage here,
// everything should already be saved or loaded by the time we call
// this function.
// Also re-wrote this function because it was messy and hard to read, always remember you write code for humans not computers so slightly longer variable names that are descriptive are really good.
// get a reference to the table
var tbl = document.getElementById('t');
// remove all the child rows, except for the header
// CSS Selector explained:
// #t - find the table by the id (you used t)
// > tr > td - find all td's that are direct children of the t table
Array.prototype.forEach.call(document.querySelectorAll('#t > tr > td'), function(node) {
node.parentNode.removeChild( node );
})
// loop over all the 'users' in 'testObject'
for(var i = 0; i < testObject.length; i++){
// store a reference to the current object to make the code easier to read
var currentObject = testObject[i];
// create the TR
var tr = document.createElement('tr');
// Create the td's
var tdUserName = document.createElement('td');
var tdEmail = document.createElement('td');
var tdPassword = document.createElement('td');
var tdLocation = document.createElement('td');
var tdOrganization = document.createElement('td');
var tdGender = document.createElement('td');
// create the text nodes
var userName = document.createTextNode(currentObject.uname);
var email = document.createTextNode(currentObject.email);
var password = document.createTextNode(currentObject.pass);
var location = document.createTextNode(currentObject.loc);
var organization = document.createTextNode(currentObject.org);
var gender = document.createTextNode(currentObject.gender);
// add the elements to their containers
tdUserName.appendChild(userName);
tdEmail.appendChild(email);
tdPassword.appendChild(password);
tdLocation.appendChild(location);
tdOrganization.appendChild(organization);
tdGender.appendChild(gender);
// add the td's to the row
tr.appendChild(tdUserName);
tr.appendChild(tdEmail);
tr.appendChild(tdPassword);
tr.appendChild(tdLocation);
tr.appendChild(tdOrganization);
tr.appendChild(tdGender);
// add the row to the table
tbl.appendChild(tr);
}
// call your clear function
clear();
}
// load the object from storage
var testObject = loadFromStorage();
// populate the table
updateTable();
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male" /> Male
<input type="radio" name="gender" id="f" value="female" /> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<!-- Added the header to the table, it isn't removed now when rebuilding it -->
<table id="t" border="1">
<thead>
<tr>
<td>Username</td>
<td>Email</td>
<td>Password</td>
<td>Location</td>
<td>Organization</td>
<td>Gender</td>
</tr>
</thead>
</table>
Here is a link to a JSFiddle because this example wont run properly because it accesses localStorage but is sandboxed. Working Example

Angularjs devade tags when user put comma

I have a case in which I need to divide tags when the user put a comma separation, for the moment the user can only add tags one by one, what I want to do is allows user to enter more than one tag in the input separated by a comma:
This is what I have now :
this is what I want to do :
what I have so far :
<div class="form-group">
<label>Mes centres d'intérêt</label>
<div class="input-group" style="margin-bottom: 8px;">
<input id="tagInsert" type="text" name="newTag" ng-model="newTag" ng-model-options="{debounce: 100}" typeahead="tag for tag in getTags($viewValue)" class="form-control" typeahead-loading="loadingTags" ng-keydown="addInterestOnEvent($event)" ng-disabled="interestLimit" autocomplete="off">
<span class="input-group-btn"><span class="btn btn-primary" ng-click="addInterest()" analytics-on="click" ng-disabled="interestLimit" analytics-event="Ajout Interet" analytics-category="Profil">Ajouter</span></span>
</div>
<p class="form__field__error" ng-show="interestLimit">Vous avez atteint la limite de 10 centres d'intérêt.</p>
<ul class="tags">
<li class="tag" ng-repeat="name in user.interests track by $index">{{ name }} <i class="icon-close" ng-click="removeInterest($index)" analytics-on analytics-event="Supprimer Interet" analytics-category="Profil"></i></li>
</ul>
</div>
My controller :
$scope.getTags = function (name) {
return $http.get('/api/tags/' + name.replace('/', '')).then(function (result) {
var tags = result.data;
for (var i = tags.length; i--; ) {
var tagName = tags[i].name;
if ($scope.user.interests.indexOf(tagName) !== -1) tags.splice(i, 1);
else tags[i] = tagName;
}
return tags;
});
};
$scope.removeInterest = function (id) {
$scope.interestLimit = false;
$scope.user.interests.splice(id, 1);
}
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value;
if (value.length) {
element.value = '';
if ($scope.user.interests.indexOf(value) === -1) {
$scope.user.interests.push(value);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
};
$scope.addInterestOnEvent = function (event) {
if (event.which !== 13) return;
event.preventDefault();
$scope.addInterest();
};
$scope.remove = function () {
$scope.confirmModal = Modal.confirm.delete(function () {
User.remove(function () {
submit = true;
Auth.logout();
$location.path('/');
});
})('votre compte');
};
You should split value with comma and do for loop.
Change "addInterest" function like this:
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value.split(',');
if (value.length) {
element.value = '';
for (var i = 0; i < value.length; i++) {
if ($scope.interestLimit) break;
if ($scope.user.interests.indexOf(value[i]) === -1) {
$scope.user.interests.push(value[i]);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
}
};
As far as I understand , you want to split text into string array by comma
Try this code please
<input id='tags' type="text" />
<input type="button" value="Click" onclick="seperateText()" />
<script>
function seperateText(){
var text= document.getElementById("tags").value;
var tags = text.split(',');
console.log(text);
console.log(tags);
}
</script>

use input type to print out the date in year-mm-dd

I have three inputs for the user with date, activity and time. In the date field when the page starts i want the day of the date printet out in the label like this for example: 2015-12-20 and the user can change it if she/he wants.. But i try to make something with a function but cant get it work.
Below is my code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="6.1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form>
Date: <input type="text" id="Datum" name="Date" value=DateTime()>
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>
<table id="myTable">
<tr>
<td>Datum</td>
<td>Aktivit</td>
<td>Tid</td>
<td>Klar?</td>
</tr>
</table>
<button id="buttonforsend" onclick="SendData()">Skicka grönmarkerad data! </button>
<script>
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
function AddRow()
{
var $check = document.createElement("INPUT");
$check.setAttribute("type", "checkbox");
$check.setAttribute("checked", "true");
$check.setAttribute("class", "checks");
$check.addEventListener("click", toggleClass);
function toggleClass() {
if (this.checked == true) {
this.parentNode.parentNode.className = "Green";
} else {
this.parentNode.parentNode.className = "Red";
}
}
var date = document.getElementById("Datum");
var activity = document.getElementById("Activity");
var time = document.getElementById("time");
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = date.value;
row.insertCell(1).innerHTML = activity.value;
row.insertCell(2).innerHTML = time.value;
row.insertCell(3).appendChild($check).value;
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 4; j++) {
var td = document.createElement('TD');
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function CheckData() {
var $arr = [];
var tb = document.getElementById("myTable");
var checks = tb.querySelectorAll(".checks"),
chk, tr;
for (var i = 0; i < checks.length; i++) {
chk = checks[i];
if (chk.checked) {
tr = chk.closest ? chk.closest('tr') : chk.parentNode.parentNode;
$arr.push({
date: tr.cells[0].innerText,
activity: tr.cells[1].innerText,
time: tr.cells[2].innerText
});
}
}
return $arr;
}
function SendData()
{
var obj = {Data: CheckData()};
var jsonString = "jsonString=" + (JSON.stringify(obj));
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","JSON_H.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xmlhttp.setRequestHeader("Content-Length", jsonString.length);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState === 4 && (xmlhttp.status === 200)){
alert(xmlhttp.responseText);
}
};
xmlhttp.send(jsonString);
}
</script>
</body>
</html>
You need to call DateTime and insert it's value in the input field, setting value=DateTime() won't set the value. For ex:
document.getElementById("Datum").value=DateTime();
Complete Code:
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
document.getElementById("Datum").value=DateTime(); // This will insert the value
<form>
Date: <input type="text" id="Datum" name="Date" value="">
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>

Form redirect on checkbox selection

Here's what i'm trying to achieve: I want to create a HTML page with a form, when you submit the form it goes to 1 of 4 locations. There is a default hidden main option thats auto-selected on page load and 2 sub-options that are optional.
Oh, and it calculates the amounts on selection!
Here's my code so far:
<html>
<head></head>
<body>
<form onSubmit="submitForm();" id="myForm" type="get">
<input id="myCheckbox1" name="myCheckbox1" type="checkbox" value="20" onClick="calcNow();" />Default option<br/>
<input id="myCheckbox2" name="myCheckbox2" type="checkbox" value="30" onClick="calcNow();" />Add-on option 1<br/>
<input id="myCheckbox2" name="myCheckbox2" type="checkbox" value="40" onClick="calcNow();" />Add-on option 2<br/>
<input id="myTotal" name="myTotal" type="text" value="" disabled="disabled" /><br/>
<input type="button" id="myButton" onClick="submitForm();" value="Continue" />
</form>
<script type="text/javascript">
var pages = [[["http://mysite.com/page1.html"],["http://mysite.com/page2.html"],["http://mysite.com/page3.html","http://mysite.com/page4.html"]]];
function calcNow()
{
var cb = document.getElementById("myCheckbox1");
var cb = document.getElementById("myCheckbox2");
var cost1 = cb.checked ? parseInt(cb.value) : 0;
var cost2 = cb.checked ? parseInt(cb.value) : 0;
var costTotal = cost1 + cost2;
document.getElementById("myTotal").value = costTotal;
var op1 = cb.checked ? 1 : 0;
if (op1 != undefined)
{
return pages[op1];
}
return undefined;
}
function submitForm()
{
var page = calcNow();
if (page != undefined)
{
alert(page);
// ---- To navigate ----
//location.href = page;
// ---- To alter post ----
//var form = document.getElementById("myForm");
//form.action = page;
//form.submit();
}
else
{
alert("Please answer all questions.");
}
}
function getRadioValue(name)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].value);
}
}
return 0;
}
function getRadioData(name, attribute)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].dataset[attribute]);
}
}
return undefined;
}
</script>
</body>
</html>
Try this
EDIT:
function submitForm()
{
//The code goes inside here, you have to decide where to redirect from if or the else
window.location.assign("http://www.w3schools.com/");
var page = calcNow();
if (page != undefined)
{
alert(page);
}
else
{
alert("Please answer all questions.");
}
}

Categories

Resources