Javascript won't calculate - javascript

Can anyone point me in the right direction as to why my calculate button will not calculate. It doesn't even throw any of the error messages up to the screen, but my clear button does work. It's probably something small, but I cannot figure it out for the life of me -_-.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("totalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("cost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
var virusRemoval = parseFloat($("virusRemoval").value = "");
var websiteMaking = parseFloat($("websiteMaking").value = "");
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value = "");
var totalCost = parseFloat($("totalCost").value = "");
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotal" value="Calculate " onblur="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>
The reason why the loop is in there is because we were required to have a loop and I couldn't find a good reason to have one, so I used one that would always be true to get it out of the way lol. Probably will throw an infinate loop at me or something, but I'll figure that out later, I'm just trying to get the dang on thing to do something here haha. I've tried to rewrite this 2 other times and still get to the same spot, so I realize it's probably something small, and I am new to Javascript. Thank you.

The problem is that you have id="calculateTotal" in the input button. Element IDs are automatically turned into top-level variables, so this is replacing the function named calculateTotal. Simply give the function a different name from the button's ID.
You also have a typo. The ID of the Total Cost field is TotalCost, but the code uses $('totalCost') and $('cost').
It's also better to do the calculation in onclick, not onblur. Otherwise you have to click on the button and then click on something else to see the result.
In the clearValues function, there's no need to assign variables and call parseFloat. Just set each of the values to the empty string. You could also just use <input type="reset">, that resets all the inputs in the form to their initial values automatically.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("TotalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("TotalCost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
$("virusRemoval").value = "";
$("websiteMaking").value = "";
$("computerOptimizationAndSetUp").value = "";
$("TotalCost").value = "";
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotalButton" value="Calculate " onclick="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>

Related

How to limit two inputs with custom maxlength?

How to limit two inputs with custom maxlength ?
I am setting a custom limit $limit = "500"; and trying to limit user words in two inputs. I want to limit first input maxlength and count words in first input, than limit second input maxlength with words left from my custom limit.
I want to set length together max length 500, one can have max 100 and one can have max 400.
and if first input has less words than 100, then add rest of the words left to the second input max length.
like : first input has 95 words in, 5 words left to reach limit.
then change second input maxlentgh to 405,
I create inputs like this :
function maxLength(el) {
if (!('maxLength' in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function() {
if (this.value.length >= max) return false;
};
}
}
maxLength(document.getElementById("title"));
function validateLength(el, word_left_field, len) {
document.all[word_left_field].value = len - el.value.length;
if (document.all[word_left_field].value < 1) {
alert("You can add max " + len + " words .");
el.value = el.value.substr(0, len);
document.all[word_left_field].value = 0;
return false;
}
return true;
}
<input type="text" id="title" name="title" maxlength="100" onChange="return validateLength(this, 'word_left', 100);" onKeyUp="return validateLength(this, 'word_left', 100);">
<input type="text" name="word_left" value="100" style="width: 25;" readonly="true" size="3">
<input type="text" id="subject" name="subject" maxlength="400" onChange="return validateLength(this, 'word_left', 400);" onKeyUp="return validateLength(this, 'word_left', 400);">
<input type="text" name="word_left" value="400" style="width: 25;" readonly="true" size="3">
so total of both inputs is 500.
I tried to set html 5 attributes pattern=".{59,60}" but they are same as setting attrbutes min and length.
But my javascript is limiting first input.
I tried several methods but didn't have a chance to make it work, would be to long question I didnt put all on here.
I belive that you need something like this:
var _maxLength = 500;
var _lengthInput = 0;
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var p = document.getElementById("total");
p.innerHTML = _maxLength;
input1.addEventListener("focus", function(e) {
this.maxLength = _maxLength + this.value.length;
_lengthInput = this.value.length;
});
input1.addEventListener("blur", function(e) {
if (_lengthInput == this.value.length)
return;
if (_lengthInput > this.value.length) {
_maxLength += _lengthInput - this.value.length;
} else {
_maxLength -= this.value.length - _lengthInput;
}
total.innerHTML = _maxLength;
});
input2.addEventListener("focus", function(e) {
this.maxLength = _maxLength + this.value.length;
_lengthInput = this.value.length;
});
input2.addEventListener("blur", function(e) {
if (_lengthInput == this.value.length)
return;
if (_lengthInput > this.value.length) {
_maxLength += _lengthInput - this.value.length;
} else {
_maxLength -= this.value.length - _lengthInput;
}
total.innerHTML = _maxLength;
});
Input 1 <input type="text" id="input1">
<br /> Input 2 <input type="text" id="input2">
<br />
<p>Characters remaining: <span id="total"></span> </p>
I hope below code helps you,
$(document).ready(function () {
$("#subject").on("keypress", function () {
var titleLength = $("#title").val().length;
var titleMaxLength = $("#title").attr("maxLength");
var titleWordLeft = titleMaxLength - titleLength
var subjectLength = $("#subject").data("charlength");
var subjectMaxLength = titleWordLeft + subjectLength;
$("#subject").attr("maxLength",subjectMaxLength);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="title" name="title" maxlength="100">
<input type="text" name="word_left" value="100" style="width: 25;" readonly="true" size="3">
<input type="text" id="subject" name="subject" data-charlength="400">
<input type="text" name="word_left" value="400" style="width: 25;" readonly="true" size="3">

Uncaught TypeError: Cannot read property 'checked' of undefined, Checkboxes

I want to validate my checkboxes to make sure that the user checked at least one, however I keep getting this error:
Uncaught TypeError: Cannot read property 'checked' of undefined.
Here is part of the HTML:
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required): <input type="text" name="userName" id="userName" required=""><br> E-Mail (Required): <input type="text" name="mail" id="mail" required=""><br> Phone (Required): <input type="text" name="phone" id="phone" required="" onchange="validNumber()"><br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other <br>
<textarea></textarea><br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and part of the JavaScript for the checkboxes:
function validChoice()
{
var bookChoice = document.userSurvey.books.value;
var x= "";
for (i=0;i< 4;i++)
{
if (document.userSurvey['bookChoice'+i].checked)
{
bookChoice = document.userSurvey['bookChoice'+i].value;
x = x +"\n"+ bookChoice;
}
}
if (bookChoice == "")
{
window.alert("You must select at least one book category.");
return false;
}
else
{
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
return true;
}
}
I am currently learning in JavaScript therefore I would prefer help in JavaScript only.
Full Code on JSFiddle:
https://jsfiddle.net/7qh5segc/
You missed some tag names and missspell them in js function:
<h1>User Survey</h1>
<h2><strong>User Information</strong></h2>
<p>Please enter your details below</p>
<br>
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required):
<input type="text" name="userName" id="userName" required="">
<br> E-Mail (Required):
<input type="text" name="email" id="email" required="">
<br> Phone (Required):
<input type="text" name="phone" id="phone" required="" onchange="validNumber()">
<br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other
<br>
<textarea></textarea>
<br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and js code goes like this:
function validName() {
var name = document.userSurvey.userName.value;
if (!/^[a-zA-Z]*$/g.test(name)) {
alert("Please enter letters a - z only");
document.userSurvey.userName.focus();
return false;
} else {
return true;
}
}
function validNumber() {
var theNumbersOnly = "";
var theChar = "";
var theInput = document.userSurvey.phone.value;
for (i = 0; i < theInput.length; i++) {
theChar = theInput.substring(i, i + 1);
if (theChar >= "0" && theChar <= "9") {
theNumbersOnly = "" + theNumbersOnly + theChar;
}
}
if (theNumbersOnly.length < 10) {
alert("You must enter 10 numbers.");
document.userSurvey.phone.focus();
} else {
var areacode = theNumbersOnly.substring(0, 3);
var exchange = theNumbersOnly.substring(3, 6);
var extension = theNumbersOnly.substring(6, 10);
var newNumber = "(" + areacode + ") ";
newNumber += exchange + "-" + extension;
document.userSurvey.phone.value = newNumber;
return true;
}
}
function validEmail() {
var email = document.userSurvey.email.value;
var atLoc = email.indexOf("#", 1);
var dotLoc = email.indexOf(".", atLoc + 2);
var len = email.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc + 2) {
return true;
} else {
alert("Please enter your e-mail address properly.");
return false;
}
}
function validChoice() {
//var bookChoice = document.userSurvey.books.value;
var bookChoice;
var x = "";
for (var i = 0; i < 4; i++) {
if (document.userSurvey.books[i].checked) {
console.log(document.userSurvey);
bookChoice = document.userSurvey.books[i].value;
x = x + "\n" + bookChoice;
}
}
if (bookChoice == "") {
window.alert("You must select at least one book category.");
return false;
} else {
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
console.log(userName);
console.log(eMail);
console.log(phoneNo);
return true;
}
}
function validAll() {
if ((validName() == true) && (validEmail() == true) && (validNumber() == true) && (validChoice() == true)) {
return true;
} else {
return false;
}
}
You missed email tag name too. regards
You can fix the checkbox issue using the following code. A sensible way to get all the checkboxes in this case is using their shared "name" attribute. There are other ways if your structure was different - e.g. using a CSS class, or adding some other custom attribute to the elements.
function validChoice() {
var bookChoices = "";
var checkboxes = document.getElementsByName("books"); //get all elements named "books" into an array
for (i = 0; i < checkboxes.length; i++) { //loop the array
if (checkboxes[i].checked) { //if the array item at this index is checked, then add it to the list
bookChoices += "\n" + checkboxes[i].value;
}
}
if (bookChoices == "") {
window.alert("You must select at least one book category.");
return false;
} else {
alert(bookChoices); //just for testing
return true;
}
}
See https://jsfiddle.net/7qh5segc/3/ for a demo using the changed validChoice() function.

how to insert id="getdobval" into input value?

I want to insert a value into <input type="text" id="getdobtval"> when I am selecting a range value.
For showing output in browser am using <span id="getdobtval"></span> instead of this span I want insert into text. How can I solve this using javascript?
jQuery(document).ready(function() {
$('#slider-bottom').slider().on('slide', function(ev) {
var finalvalue = '';
var finalbtvalue = '';
var finalbtprice = '';
var finalbitvalue = '';
finalbtprice = 250;
var newVal = $('#slider-bottom').data('slider').getValue();
var textval = parseInt(newVal);
if (textval >= 600 && textval < 6000) {
finalvalue = 0.075;
finalbitvalue = textval * finalvalue;
} else if (textval >= 6000 && textval < 30000) {
finalvalue = 0.070;
finalbitvalue = textval * finalvalue;
} else if (textval >= 30000) {
finalvalue = 0.065;
finalbitvalue = textval * finalvalue;
}
finalbtvalue = finalbitvalue / finalbtprice;
if (finalbtvalue) {
$("#getdobtval").html("<strong>" + finalbtvalue.toFixed(8) + "</strong>");
}
});
$('#slider-bottom').sliderTextInput();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<input id="slider-bottom" type="text" name="hrate" data-slider-min="600" data-slider-max="100000" data-slider-step="1" data-slider-value="600" data-slider-tooltip="show" />
<span id="getdobtval"></span>
<input type="text" id="getdobtval" name="getdobtval">
<input type="submit" name="buynow">
</form>
Create a hidden input box with different id like dobtval
<form action="" method="post">
<input id="slider-bottom" type="text" name="hrate" data-slider-min="600" data-slider-max="100000" data-slider-step="1" data-slider-value="600" data-slider-tooltip="show" />
<span id="getdobtval"></span>
<input type="hidden" id="dobtval" name="dobtval"/>
<input type="submit" name="buynow">
</form>
And in JS use,
....
if (finalbtvalue) {
$('#dobtval').val(finalbtvalue.toFixed(8));// set value in input
$("#getdobtval").html("<strong>" + finalbtvalue.toFixed(8) + "</strong>");
}
....
id must be unique, but if you want same HTML then differentiate your elements by their tag name like,
$('span#getdobtval').html('....'); // use html() span/div
$('input#getdobtval').val('....'); // use val() for input/textarea

this parameter not passing expected element

I have a dynamic set of input fields being generated. They all get named sequentially and each has an onFocus() handler. Just before each Input element is a div with a corresponding Id where I grab a dollar value from.
<input type="hidden" name="balance" value="2500.0" />
<div id="invoiceAmount0">$500.00</div>
<input type="text" size="8" id="invoiceBalance0" name="invoiceBalance0" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount1">$500.00</div>
<input type="text" size="8" id="invoiceBalance1" name="invoiceBalance1" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount2">$500.00</div>
<input type="text" size="8" id="invoiceBalance2" name="invoiceBalance2" value="" onfocus="setBalance(this)" />
The JS onFocus handler is as follows:
function setBalance(e) //e should be an input field element
{
var balance = document.PaymentForm.balance.value;
var remainder = balance;
var index = 0;
var paymentField = document.getElementById('invoiceBalance'+index); //get the first input payment element
while (paymentField != null && paymentField != e) //start with the first field and calculate the remaining balance
{
var paymentApplied = paymentField.value.replace(/[^0-9\.]+/g,"");
remainder = remainder - paymentApplied;
index++;
paymentField = document.getElementById('invoiceBalance'+index);
}
while (e == paymentField) //set the selected elements value
{
var invoiceBalance = document.getElementById('in'+index).innerHTML.replace(/[^0-9\.]+/g,"");
if (parseFloat(remainder) > parseFloat(invoiceBalance))
e.value = parseFloat(invoiceBalance).toFixed(2).toLocaleString();
else
e.value = parseFloat(remainder).toFixed(2).toLocaleString();
index++;
paymentField = document.getElementById('invoiceBalance'+index);
}
while (paymentField != null) //blank out the rest of the input fields
{
paymentField.value = '';
index++;
paymentField = document.getElementById('invoiceBalance'+index);
}
e.select();
}
The concept here is to calculate the remaining balance and set the input field's value as the user focuses the fields.
The problem is that The "this" parameter is always set to the first Input element "invoiceBalance0". I'm expecting it to be set to the element referring to it in it's onFocus handler.
What am I not seeing?
I'm unable to duplicate the error you describe, but I did notice what appears to be a typo:
var invoiceBalance = document.getElementById('in'+index).innerHTML.replace(/[^0-9\.]+/g,"");
looks like it should be
var invoiceBalance = document.getElementById('invoiceAmount'+index).innerHTML.replace(/[^0-9\.]+/g,"");
function setBalance(e) //e should be an input field element
{
var balance = document.querySelector('[name="balance"]').value;
var remainder = balance;
var index = 0;
var paymentField = document.getElementById('invoiceBalance' + index); //get the first input payment element
while (paymentField != null && paymentField != e) //start with the first field and calculate the remaining balance
{
var paymentApplied = paymentField.value.replace(/[^0-9\.]+/g, "");
remainder = remainder - paymentApplied;
index++;
paymentField = document.getElementById('invoiceBalance' + index);
}
while (e == paymentField) //set the selected elements value
{
var invoiceBalance = document.getElementById('invoiceAmount' + index).innerHTML.replace(/[^0-9\.]+/g, "");
if (parseFloat(remainder) > parseFloat(invoiceBalance))
e.value = parseFloat(invoiceBalance).toFixed(2).toLocaleString();
else
e.value = parseFloat(remainder).toFixed(2).toLocaleString();
index++;
paymentField = document.getElementById('invoiceBalance' + index);
}
while (paymentField != null) //blank out the rest of the input fields
{
paymentField.value = '';
index++;
paymentField = document.getElementById('invoiceBalance' + index);
}
e.select();
}
<input type="hidden" name="balance" value="2500.0" />
<div id="invoiceAmount0">$500.00</div>
<input type="text" size="8" id="invoiceBalance0" name="invoiceBalance0" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount1">$500.00</div>
<input type="text" size="8" id="invoiceBalance1" name="invoiceBalance1" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount2">$500.00</div>
<input type="text" size="8" id="invoiceBalance2" name="invoiceBalance2" value="" onfocus="setBalance(this)" />
It's work after changing this line :
var invoiceBalance = document.getElementById('in'+index).innerHTML.replace(/[^0-9\.]+/g,"")
To :
var invoiceBalance = document.getElementById('invoiceBalance'+index).innerHTML.replace(/[^
0-9\.]+/g,"");
that because you don't have an id like in[index] but this form invoiceBalance[index], hope that will help See
Working Fiddle.

Price Calculator in javascript with escalating prices

I am looking to make price calculator for editing papers. I have the first part complete (words per day jsfiddle ).
<label>Need in how many Days</label>
<input type="number" id="days" />
<br />
<label>Total Word Count</label>
<input type="number" id="words" />
<br />
<label>Price</label>
<input type="text" id="output" readonly />
I am looking to have the user enter the total word count and how many days they need the document, to display the price per project. I am not sure how to add the price table to the javascript and have it display the results. The table is:
250 words or less = $0.015 per word, 251-499 = $0.020 per word, 500-1499 = $0.025 per word, 1500-2499 = $0.030 per word, More than 2500 words per day = contact me
Thanks for the help. Hope that makes sense.
I have tried to do it as explicitly as possible in pure Javascript for easier understanding.
This is the HTML:
<label>Need in how many Days</label>
<input type="number" onkeyup="getValues()" id="days" />
<br />
<label>Total Word Count</label>
<input type="number" onkeyup="getValues()" id="words" />
<br />
<label>Price</label>
<input type="text" id="output" readonly />
<br />
And here is the JavaScript:
var days, words, output;
//think of the prices as t-shirt sizes
var extraSmall = 0.015,
small = 0.020,
medium = 0.025,
large = 0.030,
extraLarge = 0.035,
extraExtraLarge = 'contact me';
// now you go into the dom and get the values you need
window.getValues = function () {
var pricePerWord = 0;
days = document.getElementById('days').value;
words = document.getElementById('words').value;
if(words > 2500) {
if(days == 1) {
pricePerWord = extraExtraLarge;
} else {
pricePerWord = extraLarge;
}
} else if (words >= 1500) {
pricePerWord = large;
} else if (words >= 500) {
pricePerWord = medium;
} else if (words >= 251) {
pricePerWord = small;
} else {
pricePerWord = extraSmall;
}
// call the calculate function to do the math and update the dom
calculate(pricePerWord, words, days);
}
window.calculate = function (pricePerWord, words, days) {
var total;
if(pricePerWord === extraExtraLarge) {
total = extraExtraLarge;
} else {
total = Math.ceil(pricePerWord * words / days);
}
output = document.getElementById('output');
if(days !== '' && days != 0) {
output.value = total;
} else {
output.value = 0; // prevent 'Nan' and 'Infinity' from showing up
}
}
Note: The code uses 'window.calculate' as it makes it work in jsfidle but it should work without the 'window.' part in your code.
Hope it helps!

Categories

Resources