I'm trying to build a jacvascript running total calculator which allows the user to specify inputs which are sued to calculate a (sum) total which is shown on screen.
Before the user makes a change to the input I want to have a confirm box which allows the user to select okay (which leads to the new total being calculated) or cancel.
I've inserted the confirm box code with an IF statement into the GetTotal function but it doesn't seem to be working. Every time the new total is calculated irrespective of whether the user selects okay or cancel. Any help greatly appreciated. Mike
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.35.1/js/bootstrap-dialog.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<script>
var input1 = 5555;
var input2 = 666;
$(document).ready(function() {
document.getElementById("input1").value = input1;
document.getElementById("input2").value = input2;
GetFirstTotal();
});
function GetFirstTotal() {
var total = 0;
$('input[type=text]').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}
function GetTotal() {
var total = 0;
BootstrapDialog.confirm('Are you sure you want to do this?');
if(confirm("text")==1)
{
$('input[type=text]').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}
else {}}
</script>
TOTAL:
<div id="chkTotal"></div>
<br>
<input type="text" name="input1" id="input1"/>
<input type="button" value="Change X" onclick="GetTotal(this)"/>
<br>
<br>
<input type="text" name="input2" id="input2"/>
<input type="button" value="Change Y" onclick="GetTotal(this)"/>
The default Javascript confirm() function should return a boolean value, so you should just be able to use :
if(confirm('Are you sure you want to do this?'))
{
// Do these things
$('input[type=text]').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}
However, it appears that you are using the BootstrapDialog plug-in, which seems to operate a bit differently and accepts a callback to check the value that was entered :
So your code would likely look something like this, if you wanted to use it exclusively as a confirmation option :
BootstrapDialog.confirm('Are you sure you want to do this?', function(result){
// If result is true, then the user confirmed the message
if(result) {
// Do work here
$('input[type=text]').each(function(index, value) {
total += parseInt($(value).val() || 0);
});
$("#chkTotal").html(total);
}
});
Related
I want the nameVerification() function to throw the alert() message when the user hits submit. For example, if the user enters something like 45 in the name field, I want that alert in nameVerification() function to be called. Right now, when the user does type in a number in the name field, the alert() in the formSubmission() function is being called.
Side note:
formSubmissionfunction works perfectly. In other words, if the user enters a number < 13 in the age field, the functions alert() gets called normally with no problems. If the user enters a number > 13, it works, also, without a problem. Just thought I'd let you guys know that too.
signUp.html
<!DOCTYPE html>
<html>
<head>
<title>Signup Form</title>
<script type="text/javascript" src="signUp.js"></script>
</head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="signUp.css">
<body>
<form class="col-md-4 col-md-offset-4" name="formHandler" id="handle">
<div class="moveUsername">
<label for="usr">Name:</label>
<input type="field" class="form-control" id="nameVerify" placeholder="Username" required="required">
</div>
<div class="ageMovement">
<label for="usr" >Age (Must be 13 years or older to play):</label>
<input type="field" class="form-control" id="ageVerify" name="ageChecker" placeholder="Age" required="required">
</div>
<button type="submit" class="btn btn-default" onclick="formSubmission()" onclick="nameVerification()">Submit</button>
</form>
</body>
</html>
signUp.js
function nameVerification() {
var name = document.getElementById("nameVerify").value;
if(typeof name !== 'string') {
alert("That's not a name!");
}
}
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if(age < 13) {
alert("You're too young, you can't play the game");
}
}
age is also a string in this function:
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if(age < 13) {
alert("You're too young, you can't play the game");
}
}
If you want to do a numeric compare, you need to parse first:
function formSubmission() {
var age = document.getElementById("ageVerify").value;
if (age) {
var ageInteger = parseInt(age, 10);
if (ageInteger < 13) {
alert("You're too young, you can't play the game");
}
}
}
You have two onclick attributes on the button
<button type="submit" class="btn btn-default" onclick="formSubmission()" onclick="nameVerification()">Submit</button>
You can only have one
Your typeof test is failing because the value returned from a text input is always of type string. You can test to see if a provided text value is numeric with the following function:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
The real answer, however, is that you'll need to improve your input validation tests to determine what you want, rather than test for all the things you don't want. For example, testing for a numeric value as above would not work if someone entered "t#^!" in the field, which is likely not a value you would want in a name field. This is where regular expressions, and the built-in validations from HTML5 fields can help.
You can change your nameVerification function as follows:
function nameVerification() {
var name = document.getElementById("nameVerify").value;
if (name) {
var num = parseInt(name) || -1;
if (num >= 0 && num < 13) {
alert("That's not a name!");
}
}
}
and change your onclick values in the html to be:
onclick="formSubmission();nameVerification()"
it's because the javascript is not loaded yet.
Move:
<script type="text/javascript" src="signUp.js"></script>
To just above the </body> tag.
You should use parseInt:
var age = parseInt(document.getElementById("ageVerify").value);
I am trying to make a form that automatically sums input fields on blur and displays the sum in an inactive "Total:" field. I don't want to run anything if a user puts focus in an input then moves focus away without inputting anything and if a user does input something I want to restrict the field to only numbers. If there is a better way of doing this, please let me know. Here is an example of my current approach:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Calc</title>
<script src="javascript.js"></script>
</head>
<body>
<h1>Sales By Month</h1>
<form method="get">
<label for="january">January:</label>
<input type="text" id="january" class="amount" onblur="isNum(); calculateSum();">
<label for="february">February:</label>
<input type="text" id="february" class="amount" onblur="isNum(); calculateSum();">
<label for="total">Total:</label>
<input type="text" id="total" disabled>
</form>
</body>
</html>
JavaScript
function calculateSum() {
var elems = document.getElementsByClassName('amount');
var myLength = elems.length;
sum = 0;
for (var i = 0; i < myLength; ++i) {
sum += elems[i].value *1;
}
document.getElementById('total').value = sum;
}
function isNum() {
var amounts = parseInt(document.getElementsByClassName('amount').value);
if (isNaN(amounts) == true && amounts != '') {
alert("Please enter a numeric value");
}
}
The calculation function currently works but the "Please enter a numeric value" alert pops up every time I tab away from a field regardless of the contents.
First you need to test the value of the element that losts focus, which means you should pass it in the argument like this
onblur="isNum(this); calculateSum();"
then in your isNum function in javascript remove document.getElementsByClassName and use the argument instead ... and don't test if amounts != '' because it will never be equal to empty string while you do this amounts = parseInt(elem.value); you have to test on the elem.value
function isNum(elem)
{
var amounts = parseInt(elem.value);
if (isNaN(amounts) == true && elem.value != '') {
alert("Please enter a numeric value");
}
Here is a jsFiddle
Sounds easy probably, but not for a beginner programmer :)
I have a simple 3 field form with a submit button and a clear button. This is for a homework assignment, and we have been tasked to get the "Clear Fields" button to work properly. Here are more specific instructions:
"Add the JavaScript code for an anonymous function that's stored in a variable named clear. The function should clear the text boxes by using the $ function to get a Textbox object for each text box and then setting the value property of the textbox to an empty string. Then, add a statement in the onload event handler that attaches the clear function to the click event of the Clear Entries button."
I was able to add the statement to the onload event handler:
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
But it is the other part I am having problems with.
Add the JavaScript code for an anonymous function that's stored in a variable named clear:
var clear = function () {
Object.Method
}
Here is my full code so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateMpg = function () {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles)) {
alert("Miles: This must be a numeric value.");}
else if (miles <0) {
alert("Miles: This number must be greater than 0.");}
else if (isNaN(gallons)) {
alert("Gallons: This must be a numeric value.");}
else if (gallons <0) {
alert("Gallons: This number must be greater than 0.");}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
var clear = function () {
miles.Text = String.Empty
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
</script>
</head>
<body>
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
<label> </label>
<input type="button" id="clear" value="Clear Entries"><br>
</section>
</body>
</html>
And here is the code we were supplied with to work off of:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateMpg = function () {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles) || isNaN(gallons)) {
alert("Both entries must be numeric");
}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
</section>
</body>
</html>
You've got several issues going on:
You're mixing Javascript and jQuery in ways that don't quite work.
jQuery's methods and objects work differently than "pure"
Javascript, so be mindful of that.
The window.onload doesn't work the way you've got it. To be
consistent, do it the jQuery way with a $(document).ready() method
instead.
You're missing the # indicator on your jQuery IDs. This is
imperative or it won't find the ID of the elements you're calling.
It looks like you're mixing VB/C# code in with your javascript, such
as the String.Empty call, etc. Those objects/methods work from the
server and not in Javascript, so that's another issue (it's been a
while since I've worked in C#, so double check me on that).
Here's my solution below. I tweaked a few things to help with what I think you're going for (such as clearing ALL fields with the "Clear" button instead of just the miles field).
I understand you're a student, so don't make it a habit of coming here and trying to find people to do your homework for you. You did provide an attempt at some code, and there were a number of issues in it, so I chose to rectify them for you and explain the reasons since there were so many. Others are not as generous, but I was a struggling student once, too, so I get it when you're banging your head against the wall. :-)
$( document ).ready( function () {
var clear = function () {
miles.value = "";
gallons.value = "";
mpg.value = "";
}
var calculateMpg = function () {
var miles = parseFloat($("#miles").val());
var gallons = parseFloat($("#gallons").val());
if (isNaN(miles)) {
alert("Miles: This must be a numeric value.");
}
else if (miles <0) {
alert("Miles: This number must be greater than 0.");
}
else if (isNaN(gallons)) {
alert("Gallons: This must be a numeric value.");
}
else if (gallons <0) {
alert("Gallons: This number must be greater than 0.");}
else {
var mpg = miles / gallons;
$("#mpg").val(mpg.toFixed(1));
}
}
$("#calculate").bind("click", calculateMpg);
$("#miles").focus();
$("#clear").bind("click", clear);
});
I have a series of input fields. I never know how many, so I need to get the value from a class. In this case the class is .total.
The bestresult is a text field that gets it's value from mysql, but I want it to be changed manually or by the highest value from the other text fields.
This is the code. Does not work obviously, but maybe you get the idea of what I want to do.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$('input.total').change(function()
{
var max = $('.total').max();
$('#bestresult').attr("value", max);
});
</script>
<body>
<form>
<input type="text" name="bestresult" id="bestresult" class="total" value=""><br>
<input type="text" name="resultat[100][total]" class="total" value=""><br>
<input type="text" name="resultat[121][total]" class="total" value=""><br>
<input type="text" name="resultat[130][total]" class="total" value="">
</form>
</body>
</html>
The solution is very simple. Try this:
$('input.total').change(function()
{
var max = 0;
$('.total').each(function(){
if(parseFloat($(this).val()) > max ) {
max = parseFloat($(this).val());
}
});
$('#bestresult').val(max);
});
But if you have multiple textboxes, you should keep track of the max value and update every time change event is triggered to achieve better performance.
var max = 0;
// get the max for the first time
$(document).ready(function () {
$('.total').each(function () {
if (parseFloat($(this).val()) > max) {
max = parseFloat($(this).val());
}
});
$('#bestresult').val(max);
});
$('input.total').change(function () {
if (parseFloat($(this).val()) > max) {
max = parseFloat($(this).val());
}
$('#bestresult').val(max);
});
First, you should have your script at the end of your body, in order to have the elements defined when you bind the change event.
Then, you'd better filter the input, to exclude the one containing the max. You can use this selector : input.total[id!=bestresult].
And it would be better to bind also the keyup event, so that the max is updated without the user having to click outside.
Thus, you can have this code :
$('input.total[id!=bestresult]').on('blur change keyup', function(){
$('#bestresult').attr("value", Math.max.apply(null, $('.total[id!=bestresult]').map(function(){
return parseFloat(this.value)}).slice().filter(function(i, v){return v==v})
));
});
Demonstration
I assigned default value to textbox after the value passed by query string from
previos web page.
it looks like that:
<form method="post" name="create" onsubmit="return checkPercentValue()" style="font-size: medium; margin-top: 10%" dir="rtl" >
<input type="text" size="5px" id="stocksPercents" name="stocksPercents" value="#stocks">
</form>
Now when the user typing another value to the textbox for change the default one,
I call for javascript function to validate the value in some range (0 - 100).
the function:
<script type="text/javascript">
function checkPercentValue() {
var value = parseInt(document.getElementById("stocksPercents").getAttribute("value"));
if (value > 100 || value < 0) {
window.alert("please insert value between 0 - 100");
return false;
}
else {
return true;
}
}
</script>
So I checked why when I put value for example: 200 (greater then 100), the alert doesn't pop up(!!!)
I added to the code this line:
document.write(value);
And I saw the value allways stay the default one....and will not changed even I changed it in the
textbox before.
So I guess the problem is that typing value into the textbox can't change the default value
just like that...
what the solution to that?
thanks...
Replace this
var value = parseInt(document.getElementById("stocksPercents").getAttribute("value"));
With
var value = parseInt(document.getElementById("stocksPercents").value);
This will fix your problem.
You might also want to consider using jQuery. The syntax is easier, much shorter to type, and cross-browser compatible (that is, you don't need to worry about this b/c jQuery guarantees that for you.)
Here is your code in jQuery:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function checkPercentValue() {
var value = parseInt($("#stocksPercents").val());
if (value > 100 || value < 0) {
alert('I am GREATER');
window.alert("please insert value between 0 - 100");
return false;
}
else {
alert('I am LESS');
return true;
}
}
$(document).ready(function() {
$('#stocksPercents').blur(function() {
checkPercentValue();
// alert('Yo!');
});
});
</script>
</head>
<body>
<form method="post" name="create" onsubmit="return checkPercentValue()" dir="rtl" >
<input type="text" size="5px" id="stocksPercents" name="stocksPercents" value="#stocks">
</form>
</body></html>