Variable not updating - javascript

I have 2 files, my index and my JS file.
In my index I will have a form of input fields and my index file will be linked to my JS file.
In my JS file I will have a list of variables which will get their values from my index file input fields. I plan on then multiplying some of my values together in a function.
What is the correct way of doing this without returning NaN or undefined?
I've been trying to do by setting var values onkeyup or onclick as 'document.getelementbyid' only it never returns anything...
Some sample code would be,
HTML
<input type="radio" id="ServiceLevel" value="0.84" name="ServiceLevel"onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.67" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.56" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.28" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.14" name="ServiceLevel" onclick="getValue()"/>
and JS
var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;
// Cost Estimate
var CostEstimate = ServiceLevel * EstimatedCoreHours;
function CalculateEstimate() {
alert('test = ' +CostEstimate);
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").innerHTML=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").innerHTML=EstimatedCoreHours.toFixed(2));
}

You need to get the values in the javascript. Here is how you should do
Create a file index.htm
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<form>
<input id="a1" name="a1">
<input id="a2" name="a2">
<input id="a3" name="a3">
<input type=button onClick='Calculate()'>
</form>
</body>
</html>
script.js
function Calculate()
{
var v1 = document.getElementById ("a1").value;
var v2 = document.getElementById ("a2").value;
var v3 = document.getElementById ("a3").value;
var total = GetNumeric (v1) + GetNumeric(v2) + GetNumeric(v3);
}
function GetNumeric(val) {
if (isNaN(parseFloat(val))) {
return 0;
}
return parseFloat(val);
}

first thing is
var ServiceLevel = document.getElementById(ServiceLevel).value;
// ServiceLevel = null
this should be in function else while opening this web page getElementById will give null.
2
. your input radio button has same name & ID if this is the case which value should be taken OR they are Individual OR Group

I tried this check:
var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;
// Cost Estimate
CostEstimate = ServiceLevel * EstimatedCoreHours;
function CalculateEstimate() {
alert('test = ' +CostEstimate);
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").value=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").value=EstimatedCoreHours.toFixed(2));
}

Related

Checkboxes and localStorage

I have a list of tasks if you will and I am trying to create checkboxes that persist next to each when I go back to the page but closing the browser or hard refresh kills my selections. I have found code for saving a single checkbox but how do I iterate through the different boxes and keep them next time I enter? It seems like a really simple process but I am super-new to javascript... I could do this easily in vbscript but I would like it to work everywhere and not just IE!
New to all this so be gentle please.
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
// then enter variation of the code I found here
<script >
function save() {
//enter iteration sequence
var checkbox = document.getElementById("box");
localStorage.setItem("box", checkbox.checked);
}
//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked; <
/script>
To retrieve all elements you can use document.querySelectorAll and pass as argument the filter that will do the job. In this case you want to retrieve all htlm elements that have the type attribute value equals to checkbox. After the retrieval of all elements that have type="checkbox", you should traverse all elements of list. And for each element you should store the id of checkbox as key and the checked of the checkbox asvalue in localstorage.
Below is the code:
<script>
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
localStorage.setItem(el.id, el.checked);
console.log(el.id,el.checked);
})
}
</script>
And below is the code for updating the checkboxes with value we stored in localstorage.
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(localStorage.getItem(el.id));
document.getElementById(el.id).checked = checked;
});
If you want to use cookie to store the information instead of local storage. Link for more information: https://www.guru99.com/cookies-in-javascript-ultimate-guide.html.
function createCookie(cookieName, cookieValue, daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for (var i = 0; i < allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name) == 0)
return temp.substring(name.length, temp.length);
}
return "";
}
VERSION WITH LOCAL STORAGE
<html>
<head>
</head>
<body>
<div>
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
</div>
<script>
window.onload= function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(localStorage.getItem(el.id));
document.getElementById(el.id).checked = checked;
});
}
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
localStorage.setItem(el.id, el.checked);
console.log(el.id,el.checked);
})
}
</script>
</body>
</html>
VERSION WITH COOKIE
<html>
<head>
</head>
<body>
<div>
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
</div>
<script>
window.onload= function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(accessCookie(el.id));
document.getElementById(el.id).checked = checked;
});
}
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
createCookie(el.id, el.checked,1);//1 is the day to expire
console.log(el.id,el.checked);
})
}
function createCookie(cookieName, cookieValue, daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for (var i = 0; i < allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name) == 0)
return temp.substring(name.length, temp.length);
}
return "";
}
</script>
</body>
</html>
Just pass a different id in to document.getElementById.
Make sure to use a different key for localStorage.setItem so you don't overwrite a different value.
var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;
You could do this individually for each item or you could get all the elements of a specific class. Then loop through the elements and use their id as the local storage key.
Alternatively you could use a for loop and loop for as many items as you wish to save
On every save you can create an object with checkbox identification and values, save t in localStorage, on reloading, get the the whole object by a single key, parse it, loop through and set values
function save() {
//enter iteration sequence
var checkboxes = document.querySelectorAll("input[type=checkbox]");
var obj = {};
for (i = 0; i < checkboxes.length; i++) {
obj[checkboxes[i].id] = checkboxes[i].checked
}
localStorage.setItem("box", JSON.stringify(obj));
}
//for loading...
var checkboxesValues = JSON.parse(localStorage.getItem("box"));
Object.keys(checkboxesValues).map(key => document.getElementById(key).checked = checkboxesValues[key]);
Your code works well too if you pass right id's of inputs but there is an issue with it that for each and every input you have to add there variable you also can use for loop for that.
Your code with fixing script
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="button" value="Save" onclick="save();" />
<script>
function save() {
var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checkbox2 = document.getElementById("whatever-2");
localStorage.setItem("whatever-2", checkbox2.checked);
}
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;
var checked = JSON.parse(localStorage.getItem("whatever-2"));
document.getElementById("whatever-2").checked = checked;
</script>

How to use DOM referenced .value's in different scopes? (refactoring/scope issue)

Thanks for stopping by! I have a piece of working code here at JSFiddle
It's a basic sort of a calculator that takes 4 values, runs them through a function and spits out the result. It works as expected until I try to refactor the code. As soon as I try to refactor it at least like this, which gives me NaN or 0 whatever I do.
Here's the original code itself
<!DOCTYPE html>
<html>
<body>
See how rich you can get just flipping stuff
<input type="number" id="bp" placeholder="Buying price">
<input type="number" id="n" placeholder="Amount">
<input type="number" id="sp" placeholder="Selling price">
<input type="number" id="t" placeholder="Tax % (1 by def, 3 prem)">
<button id="button" onclick="profit()">Get rich!</button>
<input type="text" id="r" placeholder="Profit (unless ganked)">
<button id="button" onclick="resetOnClick()">More!</button><br>
<p>Thank HumbleOldMan later, go get rich now.</p>
var profit = function(){
var bp = document.getElementById("bp").value;
var n = document.getElementById("n").value;
var sp = document.getElementById("sp").value;
var t = document.getElementById("t").value;
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(result);
document.getElementById("r").value = result;
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
// just couldn't use assigned variables for DOM references for a reason. Must be scope bs or I'm just a noob//
And here is what I tried doing
<script type="text/javascript">
var bp = Number(document.getElementById("bp").value);
var n = Number(document.getElementById("n").value);
var sp = Number(document.getElementById("sp").value);
var t = Number(document.getElementById("t").value);
var r = Number(document.getElementById("r").value);
var result;
var calcProfit = function(bp,n,sp,t,r){
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(Number(result));
r = Number(result);
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
</script>
The question is common. What am I doing wrong? I definitely don't wont to settle for the fist version and get used to doing things just like that. Any assistance will be highly appreciated.
You've to get the value of input fields while after click, not on page load which will give value to NaN because initially all are empty. Get inside the calcProfit function so you'll get updated values.

Pixel to cm conversion script not working

The goal is to type in one text box a certain value (of pixels or centimeters) then to press a button, and the button to do some maths and show the result in a different text box.
What happens is, I'll get a result of 'NaN', implying that the string I inputted hadn't been converted properly. I've gone through hundreds of methods to fix this and it still doesn't work.
Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Conversion</title>
</head>
<body bgcolor=#FF0000>
<form id="conversions" name="conversions">
Pixel value :
<br>
<input type="text" name="pxvalue" id="pxvalue">
<br>
<input type="submit" name="convertcm" id="convertcm" value="Convert cm to px!">
<input type="submit" name="convertpx" id="convertpx" value="Convert px to cm!">
<br>Centimeter value :
<br>
<input type="text" name="cmvalue" id="cmvalue">
<br>
<br>Output :
<input type="text" name="output" id="output">
</form>
<!-- This is where all the JavaScript code goes -->
<script>
var form = document.getElementById("conversions");
var strcmvalue = form.elements["cmvalue"];
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue);
var pxvalue = ToInteger(strpxvalue);
var output = document.getElementById("output");
var ccmbutton = document.getElementById("convertcm").onclick = cm_to_pixel_conversion(cmvalue);
var cpxbutton = document.getElementById("convertpx").onclick = pixel_to_cm_conversion(pxvalue);
var cm_per_pixel = 0.026458333;
var px_per_cm = 37.795275591;
function pixel_to_cm_conversion(pvalue) {
cmconversion = pvalue / px_per_cm;
output.value = cmconversion.toString();
}
function cm_to_pixel_conversion(cvalue) {
pxconversion = cvalue / cm_per_pixel;
output.value = pxconversion.toString();
}
function ToInteger(x) {
x = Number(x);
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
</script>
<!-- End of the JavaScript code-->
</body>
</html>
Because you are not passing a value to the method, you are passing an html element.
var strcmvalue = form.elements["cmvalue"]; //reference element
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue); //passing element, not the value
var pxvalue = ToInteger(strpxvalue);
You need strcmvalue.value or form.elements["cmvalue"].value
Next issue is the fact you read the values when the page loads, so you will only ever have the values from the time it loads.
So you should be reading the values and converting them to numbers inside of your methods, not when the page loads.
After that your click event is calling the function, not referencing it.
var ccmbutton = document.getElementById("convertcm").onclick = function () {
var num = parseInt(strcmvalue.value, 10);
cm_to_pixel_conversion(num);
return false;
};

how to store input box number in jQuery

Imagine how a normal calculator do. Use click button to input the data in a display box. Now i want to click a button to show "+" and also remove all the number in display but store it. So I can click to show the new number. After that, store those data include number1, "+" and number 2. For example: ("1","+" "2"). The reason of doing that but not using javascript for normal calculating is because I want to use Ajax to send to php and use php to execute the maths.However, I get stuck in this part.
var memory = "";
$("#add").click(function() {
memory += $show.val() + "+";
if($show.val().length >= 1){
$show.val("+");
} else {
$show.val("");
}
}
[Obligatory warning against evaluated code from a string on a server]
I would recommend trying to get a working version of your project using only javascript before trying more advanced concepts.
var memory = [];
$("#add").click(function() {
var val = $show.val();
if (val)
memory.push(val);
$show.val('+');
});
$('#submit').click(function () {
var s = memory.join('+');
memory = [];
$.get(...
});
Check Fiddle here
var one = $("#one");
var two = $("#two");
var add = $("#add");
var show = $("#show");
var equal = $("#equal");
var memory = "";
one.click(function(){
memory += "1";
show.val("1");
});
two.click(function(){
memory += "2";
show.val("2");
});
add.click(function(){
memory += "+";
if(show.val().length >= 1)
show.val("+");
else
show.val("");
});
equal.click(function(){
show.val(memory)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="show" type="text"/>
<input id="one" type="button" value="1"/>
<input id="two" type="button" value="2"/>
<input id="add" type="button" value="+"/>
<input id="equal" type="button" value="="/>

jQuery or Javascript to parse querystring on submit

This form has multiple choices through a checkbox. Eg. Pet You Own is a multiple choice and there are various options such as Cat, Dog, Mule etc.
Now by default, the querystring sent will look like:
?pet=dog&pet=cat&pet=mule
given all 3 are checked.
I need a way to parse this so that the querystring looks like:
?pet=dog,cat,mule
Another requirement is that, there are other parameters/inputs in the form so it needs to work in conjunction with other standard form inputs.
The format you're currently seeing is the conventional format. If your form fields were named pet[] rather than pet, your server would be able to interpret the result as an array.
Having said that, to actually do what you're requesting, you could reset the name attribute of your checkboxes, so that they won't be posted, and instead post a hidden field that holds the value of your checkboxes as a comma separated string:
$('#my-form').submit(function() {
var pets = [];
$('input[name=pet]:checked').each(function() {
pets.push($(this).val());
});
// stop checkboxes from being posted
$('input[name=pet]').attr('name','');
// have an input field be posted instead
$('#my-hidden-field')
.val(pets.join(','))
.attr('name', 'pet');
});
A bit of cleaning is needed but using this with plain JS you can acheive
<html>
<head>
<title>My Page</title>
<script>
function myFunction(){
var options = "";
if(document.getElementById("option1").checked){
options = options+"Milk";
}
if(document.getElementById("option2").checked){
options = options+",Butter";
}
if(document.getElementById("option3").checked){
options = options+",Cheese";
window.location = "end.html&options="+options
}
}
</script>
</head>
<body>
<div align="center"><br>
<input id="option1" type="checkbox" name="option1" value="Milk"> Milk<br>
<input id="option2" type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input id="option3" type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
Button to submit
</body>
</html>
I suggest you to do this job on server side. When your server receive this request, it will get an array which is called pet and has three element: dog,cat and mule. you can conjunction them easily.
====
I implement this with JavaScript:
var str = window.location.href;
var queryString = "", temp = {};
str = str.substring(str.lastIndexOf("?") + 1);
str.split("&").some(function(item) {
var tarr = item.split("=");
if(typeof temp[tarr[0]] == "undefined") {
temp[tarr[0]] = tarr[1];
} else if(typeof temp[tarr[0]] == "string") {
temp[tarr[0]] += "," + tarr[1];
}
});
// Make queryString
for(var i in temp) {
queryString += "&" + i + "=" + temp[i];
}
queryString = queryString.replace(/^./,"");
//
var href = window.location.href;
console.log("before:", href);
href = href.replace(/\?.*$/, "?");
// the url is that you want
console.log("after:", href + queryString);
//window.location.href = href + queryString;
OUTPUT:
before:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog&pet=cat&pet=mule&animal=camel
after:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog,cat,mule&animal=camel
Name your check boxes as p1, p2 etc. Have a hidden field in your form named 'pet'. Just before submit using JS, set the value of your hidden variable the way you need and return true.
function beforeSubmit() {
var p = '';
if($('#p1').attr('checked')==true) p += ',cat';
if($('#p2').attr('checked')==true) p += ',dog';
...
p = p.substring(1); // strip the , at 0
$('#pet').val(p);
return true;
}
and your form should be like:
<form ... onsubmit="return beforeSubmit()">
...
<input type="checkbox" name="p1" id="p1">Cat<br>
<input type="checkbox" name="p2" id="p2">Dog<br>
...
<input type="hidden" name="pet" id="pet" value="">
</form>

Categories