I am constructing a simple calculator using a form that requires selections from a drop down which when run inputs 3 different calculations into 3 different fields. Anyway -- I have put some js in the code to prevent invalid selection combinations, using an alert to inform the user. What I would like to do is reset only the inputs (changing none of the drop downs when the user clicks "ok" on the alert box. I'm a newbie, tried several things and not come close. Any help?
<script type="text/javascript">
function clearInputs() {
document.getElementById("RawCapacity").value = "";
document.getElementById("RAIDCapacity").value = "";
document.getElementById("WindowsCapacity").value = "";
}
function RAIDcalc() {
//Values put into the calculator
var A = document.forms[0].DriveCapacity.value *1;
var B = document.forms[0].NumberOfDisks.value *1;
var C = document.forms[0].RAID.value *1;
var D = document.forms[0].HotSpare.value *1;
//Pre-math for the calculations
var E = C + D;
var F = B - E;
var G = A * 0.95;
var H = document.getElementById("RAID").options[document.getElementById("RAID").selectedIndex].text
//Validate form (to ensure selections are made),
//validate values (to prevent impossible combinations),
//and to calculate and write the responses
if (A == "null") {
alert("Please make a selection in the required fields.");
clearInputs();
}
else if (B == "null") {
alert("Please make a selection in the required fields.");
clearInputs();
}
else if (C == "null") {
alert("Please make a selection in the required fields.");
clearInputs();
}
else if (H == "RAID 5" && B<=(D + (1 * 1))) {
alert("This configuration has too many Hot Spares.");
}
else if (H == "RAID 6" && B<=(D + (2 * 1))) {
alert("This configuration has too many Hot Spares.");
else if (H == "RAID 6" && B<4) {
alert("RAID 6 requires a minimum of FOUR disks.");
}
else {
document.forms[0].RawCapacity.value = Math.round(((A * B) / 1000)*Math.pow(10,2))/Math.pow(10,2) + " TB";
document.forms[0].RAIDCapacity.value = Math.round(((F * A) / 1000)*Math.pow(10,2))/Math.pow(10,2) + " TB";
document.forms[0].WindowsCapacity.value = Math.round(((F * G) / 1000)*Math.pow(10,2))/Math.pow(10,2) + " TB";
}
//For testing
//alert("A="+A+" B="+B+" C="+C+" D="+D+" E="+E+" F="+F+" G="+G);
//var RAIDtext = document.getElementById("RAID");
//var RAIDselindex = document.getElementById("RAID").selectedIndex;
//alert (document.getElementById("RAID").options[document.getElementById("RAID").selectedIndex].text);
//if (H == "RAID 6" && B<4) alert("H = RAID 6 & B<4!");
}
</script>
Add a function to clear the input fields:
function clearInputs() {
document.getElementById("RawCapacity").value = "";
document.getElementById("RAIDCapacity").value = "";
// The same for other fields
}
and call it along with each alert() call:
if (A == "null") {
alert("Please make a selection in the required fields.");
clearInputs();
}
(Note: the condition in the if should use the == operator, which is used for comparison. = is for assignments.)
By the way, your else block is missing the curly braces, it should say:
else {
document.forms[0].RawCapacity.value = Math.round(((A * B) / 1000)*Math.pow(10,2))/Math.pow(10,2) + " TB";
document.forms[0].RAIDCapacity.value = Math.round(((F * A) / 1000)*Math.pow(10,2))/Math.pow(10,2) + " TB";
document.forms[0].WindowsCapacity.value = Math.round(((F * G) / 1000)*Math.pow(10,2))/Math.pow(10,2) + " TB";
}
Do you mean confirm()? alert() doesn't return a value, but confirm() does:
if (confirm("Do you want to do something?")) {
//Ok was pressed.
}
else {
//Cancel/close was pressed.
}
Note: if (A = "null") should be if (A == "null") same for B and C
To reset the textboxes, you can do
if (A == "null")
{
alert("Please make a selection in the required fields.");
clearTextBoxes();
}
where clearTextBoxes() would be something like
function clearTextBoxes()
{
document.forms[0].RawCapacity.value = "";
document.forms[0].RAIDCapacity.value = "";
document.forms[0].WindowsCapacity.value = "";
}
Related
I was wondering how I could output an error message telling the user to enter a whole number or a decimal number if they input a special symbol such as "#" or a character letter into the amount of my currency converter program.
Codepen
JAVASCRIPT
// Fetch exchange rate data from api
$.getJSON("https://api.fixer.io/latest?base=ZAR", function(data) {
var currencies = [];
$.each(data.rates, function(currency, rate) {
// Currency options dropdown menu
currencies.push("<option id='" + currency.toLowerCase() + "' value='" + rate + "' >" + currency + "</option>");
});
$(".currency-list").append(currencies);
})
//Calculate and output the new amount
function exchangeCurrency() {
var amount = $(".amount").val();
var rateFrom = $(".currency-list")[0].value;
var rateTo = $(".currency-list")[1].value;
if (amount == undefined || rateFrom == "--Select--" || rateTo == "--Select--") {
$(".results").html("0");
} else {
$(".results").html((amount * (rateTo * (1 / rateFrom))).toFixed(2));
}
}
You can check if the number is valid (before other checks) using one of many JS methods (regex, isNaN etc) and then show or hide some error element accordingly. Number verify methods vary when it comes to some edge/specific cases, but using "number" field alone will prevent most of the bad inputs:
pen
//Calculate and output the new amount
function exchangeCurrency() {
var amount = $(".amount").val();
var rateFrom = $(".currency-list")[0].value;
var rateTo = $(".currency-list")[1].value;
if ((amount - 0) != amount || (''+amount).trim().length == 0) {
$(".results").html("0");
$(".error").show()
} else {
$(".error").hide()
if (amount == undefined || rateFrom == "--Select--" || rateTo == "--Select--") {
$(".results").html("0");
} else {
$(".results").html((amount * (rateTo * (1 / rateFrom))).toFixed(2));
}
}
}
My code is not working properly. It is not continuing the loop. It is just showing that your value is low or high and stopping it there. Why doesn't it keep looping?
var target;
var count = 0;
var play;
var game;
function do_this() {
var choose = (Math.floor(Math.random() * 100));
target = choose + 1;
while (true) {
play = prompt("I am thinking of a no. between 1 and 100\n\n" + "enter the no.");
game = parseInt(play);
count = count + 1;
if (isNaN(game)) {
alert("Please enter integer value");
return false;
}
if ((game < 1) || (game > 100)) {
alert("Please enter the value between 1 and 100");
return false;
}
if (game < choose) {
alert("enter higher value");
return false;
}
if (game > choose) {
alert("enter lower value");
return false;
}
alert("You are correct\n\n" + "you took" + count + "to guess the game");
return true;
}
}
do_this()
You are using return false; when the value is higher or lower. Replace that with continue;
I have 3 textboxes,2 is for input value and 3rd is for operand,based on operand input it should perform relevant operation.
HTML
Num1:<input type="text" value=0 id="first" class="box1"><br>
Num2:<input type="text" value=0 id="second" class="box2"><br>
Op:<input type="text" value="+" id="oper" class="box3"><br>
<p id="demo"><b>Sum:0.00</b></p>
Onload of a document focus should be on first textbox,Validation of required fields should be done and the result should be fixed to 2 decimal places.
Jquery
$(document).ready(function () {
$("#demo").focus();
var x = parseInt($('#first').val());
var y = parseInt($('#second').val());
var z = $('#oper').val();
$("#first,#second,#oper").onkeyup(function () {
switch (z) {
case ("+"):
var a = ((x + y).toFixed(2));
$('#demo').text("Sum:" + a);
if ((isNaN(x) || x == "") && (isNaN(y) || y == "")) {
$('#demo').text("Sum:Enter a valid number!");
}
break;
case ("-"):
var b = ((x - y).toFixed(2));
$('#demo').text("Sub:" + b);
if ((isNaN(x) || x == "") && (isNaN(y) || y == "")) {
$('#demo').text("Sub:Enter a valid number!");
}
break;
case ("*"):
var c = ((x * y).toFixed(2));
$('#demo').text("Mul:" + c);
if ((isNaN(x) || x == "") && (isNaN(y) || y == "")) {
$('#demo').text("Mul:Enter a valid number!");
}
break;
case ("/"):
var d = ((x / y).toFixed(2));
$('#demo').text("Div:" + d);
if ((isNaN(x) || x == "") && (isNaN(y) || y == "")) {
$('#demo').text("Div:Enter a valid number!");
}
break;
default:
$('#demo').text("Invalid operator");
}
});
});
Trying to fix out the errors,please anyone can help me!!
As Tushar said, the event is handled using keyup, not onkeyup.
You need to move the variable assignments into the keyup handler, as you want them to be re-calculated every time they change.
$(document).ready(function () {
$("#first").focus();
$("#first,#second,#oper").keyup(function () {
var x = parseInt($('#first').val());
var y = parseInt($('#second').val());
var z = $('#oper').val();
switch (z) {
....
To focus on the first textbox, you want to focus on the first textbox id, rather than the p tag.
$("#first").focus();
This will then work like you expect.
I have fixed this issue you can check on js fiddle please tell me if you have any issue.
link here -- http://jsfiddle.net/FHf9a/317/
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
My form does not seem to be validating or submitting. It was submitting and validating before, but the Jquery error messages were not all displaying at the same time so I had to edit the code, and now it is not submitting or validating at all.
Here is my JS:
function validateUserName(user)
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
return "You Left the Username field Emptyyy";
}
else if (uLength <4 || uLength > 11)
{
return "The Username must be between 4 and 11 characters";
}
else if (illegalChars.test(u))
{
return "The Username contains illegal charectors men!";
}
else
{
return "";
}
}
function validatePassword(pwd)
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
return "You left the password field empty";
}
else if (pLength < 6 || pLength > 20)
{
return "Your password must be between 6 and 20 characters in length";
}
else if (p != cP)
{
return "The passwords do not match!"
}
else
{
return "";
}
}
function validateEmail(email)
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (eLength == "" || eLength == null)
{
return "You left the email field blank!";
}
else if (e.match(illegalChars))
{
return "ILEGAL CHARECTORS DETECTED EXTERMINATE";
}
else
{
return "";
}
}
function validateFirstName(fname)
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if(fLength > 20)
{
return "First Name has a max of 20 characters";
}
else if (illegalChars.test(f))
{
return "Numbers,letter and underscores in first name only";
}
else
{
return "";
}
}
function validateLastName(lName)
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if(lLength > 100)
{
return "Last Name has a max of 100 characters";
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only";
}
else
{
return "";
}
}
function validateForm()
{
/*
valid = true;
//call username function
valid = valid && validateUserName();
//call password function
valid = valid && validatePassword();
//call email function
valid = valid && validateEmail();
//call first name function
valid = valid && validateFirstName();
//call first name function
valid = valid && validateLastName();
return valid;
*/
var error = "";
//call username function
error += "\n"+validateUserName();
//call password function
error += "\n"+validatePassword();
error += "\n"+validateEmail();
error += "\n" + validateFirstName();
error += "\n" + validateLastName();
if(error === ""){
return true;
}
else{
$("#ErrorUser").text(error);
$("#ErrorEmail").text(error);
$("#ErrorFname").text(error);
$("#ErrorPassword1").text(error);
$("#ErrorLname").text(error);
return false;
}
}
$('#your-form').submit(validateForm);
Fiddle: http://jsfiddle.net/cyKgD/
You had few errors in your code.
The validateForm() is never being called
Line 174: Should be else if (illegalChars.test(l))
Line 113: Closing bracket missing
This fiddle seems to be working now, http://jsfiddle.net/u5565/
Make sure that jQuery is included in your page. The line of code
$(function() {
$('#your-form').submit(function() {
return validateForm();
});
});
tells jQuery to validate the form when it is submitted.
In your fiddle, you forgot method="POST" on the form tag
<form name = "NewUser" id = "your-form" method="POST">
I have this input tag where you put the total of your receipt :
<input type="text" name="currency" id="currency" class="text-input" onBlur="this.value=formatCurrency(this.value);" />
The Javascript is as follows:
<script type="text/javascript">
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)) {
num = "0";
}
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num % 100;
num = Math.floor(num/100).toString();
if(cents < 10) {
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
}
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
</script>
Users can only enter receipts more than $10.00 bucks, how can I set that on my script? Also they need to know they can not enter currency less than $10.
From what I can gather from your question I think you are looking for something like this. Basically if we have a valid entry such as $100.00 we continue, return true etc, else if we have something that looks like an int or float we can reformat this and recurse the function, else hint user for of vaild entry
var foo = document.getElementById('foo');
foo.addEventListener('blur', function(e) {
var val = e.target.value;
var err = document.getElementById('err');
var errMsg = 'please enter a value $10.00 or greater';
var patt = /^\$\d+\.\d{2}$/;
var amount = parseInt(val.replace(/\$|\./g, ''));
if (val !== '') {
if (patt.test(val)) {
if (amount < 1000) {
err.textContent = errMsg;
} else {
document.getElementById('suc')
.textContent = 'processing request';
}
} else if (typeof amount == 'number' && !/[a-z]/g.test(val)) {
if (/\.\d{2}/.test(val)) {
e.target.value = '$' + (amount / 100);
} else {
e.target.value = '$' + amount + '.00';
}
arguments.callee(e);
} else {
err.textContent = errMsg;
}
}
});
here is a demo
You can apply a validation function when submitting the form to test if the value is below a threshold, such as:
function validate()
{
value = document.getElementById('currency');
if (value <= 10.00)
{
return false
} else
{
return true;
}
}
You could also apply this to the onblur event, but my preference is to present validation errors when the form is submitted.
It looks like you're trying to parse a string, convert it nicely into dollars and cents, and reject it if it's less than 10. There's a much nicer way to do that:
function formatCurrency(num) {
// Remove the dollar sign
num = num.replace("$", "");
// Change the string to a float, and limit to 2 decimal places
num = parseFloat(num);
Math.round(num * 100) / 100;
// If its less than 10, reject it
if(num < 10) {
alert("Too small!");
return false;
}
// Return a nice string
return "$" + num;
}
At the end, are you trying to return -$99.94 if the number is negative?