Can someone explain to me or figure it out. I dont know where I made a mistake here. I have javascript and html code where I get input from user for a flight. I want to make a counter to count all flights function counter() but it gives me the value of name. And another problem is I want when I click on the Accept button to make the background of the div element green function changeColor().
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
var btn1 = document.createElement("BUTTON");
var btn2 = document.createElement("BUTTON");
var t1 = document.createTextNode("Accept");
var t2 = document.createTextNode("Reject");
btn1.appendChild(t1);
btn2.appendChild(t2);
divForOutput.innerHTML += name.value +", " + plainNum.value +"<br>" + "Radius: " + radius.value +", "+"Altitude: "+altitude.value+"<br>"+type.value+"<br>";
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
btn1.setAttribute('onclick','changeColor(this);');
btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
var parentofChild = document.getElementById("output");
output.div.background = green;
}
function counter(){;
var sum = document.getElementsByClassName("printing");
var counter = 0;
for(var i = 0;i <sum.length;i++){
counter+=parseInt(sum[i].innerHTML);
}
document.getElementById("total").innerHTML = counter;
}
<h1>Register flight</h1>
<form>
<div>
<label>Name and surname</label>
<input type="text" id="name">
</div>
<div>
<label>Number plate</label>
<input type="text" id="plainNum">
</div>
<div>
<label>Coordinates</label>
<input type="text" id="coordinates">
</div>
<div>
<label>Radius</label>
<input type="text" id="radius">
</div>
<div>
<label>Altitude</label>
<input type="text" id="altitude">
</div>
<div>
<label>Type</label>
<select id="type">
<option value="Comercial">Comercial</option>
<option value="Buissines">Buissines</option>
</select>
</div>
<div>
<input type="button" value="Submit" onclick="addRow();">
</div>
</form>
<divи>
<h3>Registered flights</h3>
<p>Total:<span id="total">0</span></p>
</div>
<div id="output">
</div>
Below I've fixed some of the code and made things a bit better.
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
//var btn1 = document.createElement("BUTTON");
//var btn2 = document.createElement("BUTTON");
//var t1 = document.createTextNode("Accept");
//var t2 = document.createTextNode("Reject");
//btn1.appendChild(t1);
//btn2.appendChild(t2);
divForOutput.innerHTML = `
${name.value}<br>
Radius: ${radius.value}<br>
Altitude: ${altitude.value}<br>
${type.value}<br>
<button onclick="changeColor();">Accept</button>
<button onclick="disableButtons();">Reject</button>
`;
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
//btn1.setAttribute('onclick','changeColor(this);');
//btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
const output = document.getElementById("output");
output.style.backgroundColor = "green";
}
function counter(){;
const sum = document.getElementsByClassName("printing");
const counter = sum.getElementsByTagName('div').length;
return document.getElementById("total").innerHTML = counter;
}
There is an explanation for the background color here
As for the counter; what I did was count the div elements inside of the output div. That will give you the amount of flights a user has.
Your color setting had several problems. You don't use output.div.background to set the color, and you were using the undefined variable green instead of the string "green". This works:
function changeColor(){
var output = document.getElementById("output");
output.style.backgroundColor = 'green';
}
I don't know what you are trying to count with your counter function, so I can't fix that.
Related
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
So no matter what I change if I input anything in the textarea it is not reading anything from the form.
I needed it to be able to have input and not just change the default message of the textarea. If there is any other error in my code please help me by correcting me. And this is only purely html and javascript.
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").innerHTML;
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").innerHTML = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
Try value instead of innerHTML for textarea control.
function findReplace() {
var str = document.getElementById("message").value; //use value here
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res; //use value here
}
Note: There is no element with id demo in the HTML which is used in your JS.
Demo:
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").value;
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
//document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
I'm having trouble working with my next button on my webpage. I can get the other parts of the page (the answer message) to show up fine with when the button is clicked, but for some reason it will not work with this next button. Hiding it works fine, but when I click the button the next button will not show up. If I don't hide or style = "none", the button shows up fine. I've tried .style = "none" & .style = "block" and .visibility = "hidden" and .visibility = "visible", with no success. If anyone could give me some insight I'd appreciate it!
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky() {
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
} else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next() {
};
<div class="user-response">
What is <input type="text" id="user_answer"> ?
<button onclick="clicky()" type=b utton>Submit</button>
<button onclick="next()" type=s ubmit id="next">Next -></button>
</div>
<p id="correct">{{clue.answer}}</p>
<p id="score">{{score}}</p>
<p id="value">{{clue.worth}}</p>
<form method="GET">
<input type="hidden" name="score_get" value=0>
</form>
<div class="answer" id="answer">
</div>
At the end of the clicky function you are trying to set the innerHTML of a missing element "showed_score", It results with an error and quit the function before it is done.
Just remove this line or add the element to your html
I created this interactive snippet. Looks like there is an error (Uncaught TypeError: Cannot read property 'innerHTML' of null) happening right above that is throwing console errors. Based on your code the elements showed_score and score_get do not exist. Fixing this will hopefully fix your original problem.
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id = "next">Next -></button>
</div>
<p id = "correct"></p>
<p id = "score"></p>
<p id = "value"></p>
<form method = "GET">
<input type = "hidden" name = "score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>
<script type = "text/javascript">
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next(){
};
</script>
I don't know what template engine youre using to render {{clue.answer}} but I imagine there's an answer in there somewhere. Try the following code instead (you were missing an id reference for getElementById :
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id = "next">Next -></button>
</div>
<p id = "correct">{{clue.answer}}</p>
<p id = "score">{{score}}</p>
<p id = "value">{{clue.worth}}</p>
<form method = "GET">
<input type = "hidden" name = "score_get" id="score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>
<div id="showed_score">
</div>
<script type = "text/javascript">
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + Math.floor(score);
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
}
function next(){
}
</script>
Try commenting these 2 lines:
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
They trigger an error which prevents the button from becoming visible.
You probably have an error before it gets to the code for visibility.
Look in your console to find errors and what is causing it.
Here's your example with most of it commented out and it works:
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
//var correct = document.getElementById("correct").innerHTML;
//var score = document.getElementById("score").innerHTML;
//var value = document.getElementById("value").innerHTML;
//var val2 = value.substring(1);
//var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
//document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
//score -= worth;
}
//document.getElementById("showed_score").innerHTML = "Score is now $" + score;
//document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next(){
};
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id="next">Next -></button>
</div>
<p id = "correct">{{clue.answer}}</p>
<p id = "score">{{score}}</p>
<p id = "value">{{clue.worth}}</p>
<form method = "GET">
<input type = "hidden" name = "score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>
the user need to write the name of the animal, and I need to output the name+animalCode connected.
For some reason I am not getting any output.
Here is the code:
var str = "Cow12,Dog3,Cat721,Lion532";
var getInput = document.getElementById("inp1");
var getSubmit = document.getElementById("subm1");
getSubmit.onclick = function() {
var input = getInput;
var firstPlace = str.indexOf(input);
var numPlace = str.indexOf(",", firstPlace);
var newWord = str.slice(firstPlace, numPlace);
document.getElementById("print").innerHTML = newWord;
};
<form>
<input id="inp1" type="text">
<input id="subm1" type="submit">
</form>
<p id="print"></p>
Thank you very much for the help ! :)
You are just missing the .value part.
var str = "Cow12,Dog3,Cat721,Lion532";
var getInput = document.getElementById("inp1");
var getSubmit = document.getElementById("subm1");
getSubmit.onclick = function(event) {
event.preventDefault();
var input = getInput.value;
var firstPlace = str.indexOf(input);
var numPlace = str.indexOf(",", firstPlace);
var newWord = str.slice(firstPlace, numPlace);
document.getElementById("print").innerHTML = newWord;
};
<form>
<input id="inp1" type="text">
<input id="subm1" type="submit">
</form>
<p id="print"></p>
Make the following change :
Remove form tag as there is no need for that.
var str = "Cow12,Dog3,Cat721,Lion532";
function getSubmit()
{
var input = document.getElementById("inp1").value;
var firstPlace = str.indexOf("",input);
var numPlace = str.indexOf(",", firstPlace);
var newWord = str.slice(firstPlace, numPlace);
document.getElementById("print").innerHTML = newWord;
}
<input id="inp1" type="text">
<button id="subm1" onclick="getSubmit()">Submit</button>
<p id="print"></p>
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
function fuelPrice()
{
var fuelPrice=0;
var theForm = document.forms["price"];
var withFuelPrice = document.getElementsByClassName("ful");
if(withFuelPrice.checked==true)
{
fuelPrice=30;
}
return fuelPrice;
}
function withPol()
{
var polishPrice=0;
var theForm = document.forms["price"];
var includeInscription = document.getElementsByClassName("pol");
if(includeInscription.checked==true){
polishPrice=50;
}
return polishPrice;
}
function driver()
{
var driverPrice=0;
var theForm = document.forms["price"];
var getDriv = document.getElementsByClassName("drv");
if(getDriv.checked==true){
driverPrice=50;
}
return driverPrice;
}
function calculateTotal()
{
var car1= 50
var total = fuelPrice() + withPol() + car1 + driver();
var text = "Total Price For the Renting "+total+ "BHD/Week";
//display the result
var divobj = document.getElementsByClassName('totalPrice');
divobj.style.display='block';
divobj.innerHTML = text;
return text;
}
function myFunction()
{
var name = calculateTotal()
confirm(name)
}
<form class="price"><p class="totalPrice booktxt">Total Price For the Renting 50BHD/Week<br> </p>
<input onclick="calculateTotal() " type="checkbox" class="ful">With Fuel<br>
<input onclick="calculateTotal() " type="checkbox" class="pol">Polishing 2 weeks<br>
<input onclick="calculateTotal() " type="checkbox" class="drv">Driver<br>
</form>
<button class="btn1" onclick="myFunction()">Add to cart</button>
I am having some issues to make the price appear in confirm so the user sees the price and confirm its ok or not when i click it show a blank popup. Also, can I know my mistake to avoid it in the future
You have to return something to show in that confirm box.
function fuelPrice() {
var fuelPrice = 0;
var theForm = document.forms["price"];
var withFuelPrice = theForm.elements["ful"];
if (withFuelPrice.checked == true) {
fuelPrice = 30;
}
return fuelPrice;
}
function withPol() {
var polishPrice = 0;
var theForm = document.forms["price"];
var includeInscription = theForm.elements["pol"];
if (includeInscription.checked == true) {
polishPrice = 50;
}
return polishPrice;
}
function driver() {
var driverPrice = 0;
var theForm = document.forms["price"];
var getDriv = theForm.elements["drv"];
if (getDriv.checked == true) {
driverPrice = 50;
}
return driverPrice;
}
function calculateTotal() {
var car1 = 50
var total = fuelPrice() + withPol() + car1 + driver();
var text = "Total Price For the Renting " + total + "BHD/Week"; // Store text in local variable
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = text;
return text; // Return text
}
function myFunction() {
var name = calculateTotal()
confirm(name) // Now it shows text from calculateTotal function
}
<form id="price">
<p id="totalPrice" class="booktxt">Total Price For the Renting 50BHD/Week<br> </p>
<input onclick="calculateTotal() " type="checkbox" id="ful">With Fuel<br>
<input onclick="calculateTotal() " type="checkbox" id="pol">Polishing 2 weeks<br>
<input onclick="calculateTotal() " type="checkbox" id="drv">Driver<br>
</form>
<button class="btn1" onclick="myFunction()">Add to cart</button>
Just add a return value to calculateTotal function. Like the following
return divobj.innerHTML;
Full function looks as follows:
function calculateTotal()
{
var car1= 50
var total = fuelPrice() + withPol() + car1 + driver();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For the Renting "+total+ "BHD/Week";
return divobj.innerHTML;
}