Arithmetic operations using Jquery - javascript

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/

Related

Javascript: Where do i add the redirection?

I just need my form to redirect the user to another page after validation using javascript.
Here is my code:
function checkEnq() {
var x = document.forms["enq"]["email"].value;
var y = document.forms["enq"]["dB"].value;
var z = document.forms["enq"]["textF"].value;
if (x == null || x == "" || y == null || z == null || z == "") {
alert("Please make sure all fields are entered.");
}
}
How do i add the location.href or window.open once the js has checked that all fields (email, dB,& textF) are filled?
i can add target="_blank" action="./result.html" to the <form> field and it will still redirect to the result page even if the form is not filled up completely.
Add a "else" block
function checkEnq() {
var x = null;
var y = null;
var z = null;
try {
x = document.forms["enq"]["email"].value;
y = document.forms["enq"]["dB"].value;
z = document.forms["enq"]["textF"].value;
} catch(e) {
alert('code error');
};
if (x == null || x == "" || y == null || z == null || z == "") {
alert("Please make sure all fields are entered.");
} else {
document.location.href="/redirect.page"
}
}
I solved it by using this window.open("./page.html") instead of document.location.href

Input removing leading 0

I have a form input field.
<input style="text-align:right;" type="text" name="DiversionCalc_Diversion_Rate" id="calc_dr" value="0.25%" />
I am attempting to format it based on focusout using jQuery 1.7.2
$('#calc_dr').focusout(function () {
var value = $.trim($(this).val()).toString();
if (value.indexOf("0.") === -1) {
var $t = ("0" + value).toString();
alert($t);
$(this).val($t);
}
if (value != '' && value.indexOf("%") === -1) {
$(this).val(value + '%');
}
});
While this mostly is working, the alert pops up the correct 0.25 when I enter .25 in the field, however, the $(this).val only ever shows .25
How can I get it to show what it's showing me in the alert???
Make $t a global variable (pull it out of the if loop) and assign it instead of value.
$('#calc_dr').focusout(function () {
var value = $.trim($(this).val()).toString();
var $t = value;
if (value.indexOf("0.") === -1) {
$t = ("0" + value).toString();
alert($t);
$(this).val($t);
}
if ($t != '' && $t.indexOf("%") === -1) {
$(this).val($t + '%');
}
});
The basic idea is to grab the value, manipulate the value, then update the UI. The key being there is only one update at the end.
// Get the new value (strip everything but numbers and period)
var v= parseFloat($(this).val().toString().replace(/[^0-9\.]+/g, ""));
// Basic data type validation
if (isNaN(v)) v= 0;
if (v< 0) v= 0;
if (v> 100) v= 100;
// other validation updates v as needed...
doCheckDiversionRate(v);
// update UI (btw toFixed() will add a leading zero)
$(this).val(v.toFixed(2) + '%');

Jquery keydown() with number format not work correctly on android webview

I have encountered a strange behavior on android browser / webview. I was testing an input that will automatically format to phone number format "(xxx) xxx-xxxx". But then what happened was when I tapped or press any number on androids keyboard, the first input was like this "(x" but then the cursor was in between "(" and "x". Is there a way to put the cursor after "x" value?
I tested this on iPhone and windows web browsers and it works fine. Please let me know if there are mistakes on my jquery or javascripts.
Thanks
HTML CODE:
<html>
<head>
<title>Sample Phone Number Format</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
<input type="text" id="phone" />
<script type="text/javascript">
$('#phone').on('keydown', function (event) {
objval = $(this).val();
if (event.keyCode == 46 || event.keyCode == 8) {} else {
if (!((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode > 95 && event.keyCode < 106) || (objval.length > 13))) {
event.preventDefault();
} else {
if (objval.length == 0) {
$(this).val(objval + '(');
alert(objval + '(');
} else if (objval.length == 4) {
$(this).val(objval + ') ');
alert(objval + ') ');
} else if (objval.length == 9) {
$(this).val(objval + '-');
alert(objval + '-');
} else if (objval.length >= 14) {
if (event.keyCode == 9) {
return;
} else {
event.preventDefault();
}
}
}
}
});
$('#phone').on('keydown', function (event) {
var objVal = $(this).val();
if(objVal.length < 14)
{
validateCallerForm(objVal + String.fromCharCode((96 <= event.keyCode && event.keyCode <= 105)? event.keyCode-48 : event.keyCode));
}
});
//Validates proper phone format, true if valid phone number, false otherwise
function isValidPhoneNumber(elementValue) {
var numberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
return numberPattern.test(elementValue);
}
//validates entire caller form, also updates css classes for proper response
function validateCallerForm(PhoneNumber) {
if (isValidPhoneNumber(PhoneNumber)) {
alert("true");
} else {
alert("false");
}
}
</script>
</body>
</html>
Giving +50 Bounty to who'm will answer this correctly
you have to first define listener for typing and copy-paste like below (not required) :
$("#phone").keyup( function() {
maskLine(this);
});
$("#phone").change( function() {
maskLine(this);
});
Then, to manage cursor placement, you have to cache previous phone number and then, you could compare difference and update cursor position if needed.
So declare, you have to declare a global array like this :
var _cacheElementValues = new Array();
At last, you can check the function below, it applies your mask to phone number field and manage cursor placement :
function maskLine( element ) {
element = $(element);
var maskedLine = '';
var line = element.attr('value');
// check the cache of the input and abord if no change since last treatment
if (_cacheElementValues[element.attr('id')] != undefined && _cacheElementValues[element.attr('id')] == line) {
return;
}
line = line.replace(/\D/g, ''); // remove all characters != digits
line = line.substring(0, 10);
if (line != '') {
// apply mask
if (line.length <= 2 ) {
maskedLine = "(" + line;
} else if (line.length < 6) {
maskedLine = line.replace(/^([0-9]{3})([0-9]{0,3})/g, '($1) $2');
} else {
// mask : '(XXX) XXX-XXXX'
maskedLine = line.replace(/^([0-9]{3})([0-9]{3})([0-9]{0,4})/g, '($1) $2-$3');
}
}
// define cursor position at the end of the input by default
var pos = maskedLine.length;
// Change cursor placement if necessary
if (typeof element[0].selectionStart != 'undefined') {
var start = element[0].selectionStart;
var end = element[0].selectionEnd;
var insText = element[0].value.substring(start, end);
// get current cursor placement
if (insText.length == 0) {
pos = start;
} else {
pos = start + insText.length;
}
// find how many digits typing since last mask application
var previousLength = 0;
if (_cacheElementValues[element.attr('id')] != undefined) {
previousLength = _cacheElementValues[element.attr('id')].replace(/\s/g, '').length;
}
var diff = maskedLine.replace(/\s/g, '').length - previousLength;
// if sum of new typing digit is > 0 : we change cursor placement
if (diff > 0) {
pos += (diff - 1) + Math.round((diff-1)/3);
if (pos%6 == 0 && maskedLine.length >= pos+1) pos++;
}
}
// update input data & cache
element.val(maskedLine);
_cacheElementValues[element.attr('id')] = maskedLine;
// update cursor placement
element[0].selectionStart = element[0].selectionEnd = pos;
}
You can find this example on jsFiddle : http://jsfiddle.net/UE9LB/5/
I hope this little explantion can solve your problem ;)
Enjoy !
ps: i apologize for my poor english :s
I'd recommend at least starting with an existing plugin rather than going through your own isolated rounds of solving issues.
http://digitalbush.com/projects/masked-input-plugin/
https://github.com/igorescobar/jQuery-Mask-Plugin
The short answer is to set the selectionStart and selectionEnd properties of the input element. After you format the value, set these properties to this.value.length.
this.selectionStart = this.value.length;
this.selectionEnd = this.value.length;
But, where you are going to run into trouble is when the cursor is not at the end of the text. Eg, the user has manually positioned the cursor to a position within the text. To prevent the cursor from jumping to the end, you will need to detect the cursor position before you format the input, then put the cursor back in the appropriate position after formatting.
Edit: This jsFiddle may get you started, but isn't perfect yet.
I rewrite the code on my #phone keydown event and this will work on iPhone, Android, webkit browsers.
$('#phone').on('keydown', function (event) {
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39) {
// ignore if BKSPCE, left arrow, or right arrow
} else {
// validate if anything else
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0,3);
var next3 = string.substring(3,6);
var next4 = string.substring(6,10);
var string = ("(" + first3 + ") " + next3 + "-" + next4);
$(this).val(string);
}
});

Phone mask with jQuery and Masked Input Plugin

I have a problem masking a phone input with jQuery and Masked Input Plugin.
There are 2 possible formats:
(XX)XXXX-XXXX
(XX)XXXXX-XXXX
Is there any way to mask it accepting both cases?
EDIT:
I tried:
$("#phone").mask("(99) 9999-9999");
$("#telf1").mask("(99) 9999*-9999");
$("#telf1").mask("(99) 9999?-9999");
But it doesn't works as I would like.
The closest one was (xx)xxxx-xxxxx.
I would like to get (xx)xxxx-xxxx when I type the 10th number, and (xx)xxxxx-xxxx when I type the 11th. Is it posible?
Try this - http://jsfiddle.net/dKRGE/3/
$("#phone").mask("(99) 9999?9-9999");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 );
$(this).val( first + '-' + lastfour );
}
});
Here is a jQuery phone number mask. No plugin required.
Format can be adjusted to your needs.
Updated JSFiddle.
HTML
<form id="example-form" name="my-form">
<input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX">
</form>
JavaScript
$('#phone-number', '#example-form')
.keydown(function (e) {
var key = e.which || e.charCode || e.keyCode || 0;
$phone = $(this);
// Don't let them remove the starting '('
if ($phone.val().length === 1 && (key === 8 || key === 46)) {
$phone.val('(');
return false;
}
// Reset if they highlight and type over first char.
else if ($phone.val().charAt(0) !== '(') {
$phone.val('('+$phone.val());
}
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
Actually the correct answer is on http://jsfiddle.net/HDakN/
Zoltan answer will allow user entry "(99) 9999" and then leave the field incomplete
$("#phone").mask("(99) 9999-9999?9");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 5 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") + 1, 1 );
var lastfour = last.substr(1,4);
var first = $(this).val().substr( 0, 9 );
$(this).val( first + move + '-' + lastfour );
}
});​
You need a jQuery plugin for the mask works as well.
-- HTML --
<input type="text" id="phone" placeholder="(99) 9999-9999">
<input type="text" id="telf1" placeholder="(99) 9999*-9999">
<input type="text" id="telf2" placeholder="(99) 9999?-9999">
-- JAVASCRIPT --
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<script>
$(document).ready(function($){
$("#phone").mask("(99) 9999-9999");
$("#telf1").mask("(99) 9999*-9999");
$("#telf2").mask("(99) 9999?-9999");
});
</script>
You can use the phone alias with Inputmask v3
$('#phone').inputmask({ alias: "phone", "clearIncomplete": true });
$(function() {
$('input[type="tel"]').inputmask({ alias: "phone", "clearIncomplete": true });
});
<label for="phone">Phone</label>
<input name="phone" type="tel">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.numeric.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.date.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.phone.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/jquery.inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/phone-codes/phone.js"></script>
https://github.com/RobinHerbots/Inputmask#aliases
Using jQuery Mask Plugin there is two possible ways to implement it:
1- Following Anatel's recomendations:
https://gist.github.com/3724610/5003f97804ea1e62a3182e21c3b0d3ae3b657dd9
2- Or without following Anatel's recomendations:
https://gist.github.com/igorescobar/5327820
All examples above was coded using jQuery Mask Plugin and it can be downloaded at:
http://igorescobar.github.io/jQuery-Mask-Plugin/
var $phone = $("#input_id");
var maskOptions = {onKeyPress: function(phone) {
var masks = ['(00) 0000-0000', '(00) 00000-0000'];
mask = phone.match(/^\([0-9]{2}\) 9/g)
? masks[1]
: masks[0];
$phone.mask(mask, this);
}};
$phone.mask('(00) 0000-0000', maskOptions);
With jquery.mask.js
http://jsfiddle.net/brynner/f9kd0aes/
HTML
<input type="text" class="phone" maxlength="15" value="85999998888">
<input type="text" class="phone" maxlength="15" value="8533334444">
JS
// Function
function phoneMask(e){
var s=e.val();
var s=s.replace(/[_\W]+/g,'');
var n=s.length;
if(n<11){var m='(00) 0000-00000';}else{var m='(00) 00000-00000';}
$(e).mask(m);
}
// Type
$('body').on('keyup','.phone',function(){
phoneMask($(this));
});
// On load
$('.phone').keyup();
Only jQuery
http://jsfiddle.net/brynner/6vbrqe6z/
HTML
<p class="phone">85999998888</p>
<p class="phone">8599998888</p>
jQuery
$('.phone').text(function(i, text) {
var n = (text.length)-6;
if(n==4){var p=n;}else{var p=5;}
var regex = new RegExp('(\\d{2})(\\d{'+p+'})(\\d{4})');
var text = text.replace(regex, "($1) $2-$3");
return text;
});
The best way to do this is using the change event like this:
$("#phone")
.mask("(99) 9999?9-9999")
.on("change", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 ); // Change 9 to 8 if you prefer mask without space: (99)9999?9-9999
$(this).val( first + '-' + lastfour );
}
})
.change(); // Trigger the event change to adjust the mask when the value comes setted. Useful on edit forms.
The best way to do it on blur is:
function formatPhone(obj) {
if (obj.value != "")
{
var numbers = obj.value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:' - '};
obj.value = '';
upto = numbers.length;
if(numbers.length < 10)
{
upto = numbers.length;
}
else
{
upto = 10;
}
for (var i = 0; i < upto; i++) {
obj.value += (char[i]||'') + numbers[i];
}
}
}
As alternative
function FormatPhone(tt,e){
//console.log(e.which);
var t = $(tt);
var v1 = t.val();
var k = e.which;
if(k!=8 && v1.length===18){
e.preventDefault();
}
var q = String.fromCharCode((96 <= k && k <= 105)? k-48 : k);
if (((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=8 && e.keyCode!=39) {
e.preventDefault();
}
else{
setTimeout(function(){
var v = t.val();
var l = v.length;
//console.log(l);
if(k!=8){
if(l<4){
t.val('+7 ');
}
else if(l===4){
if(isNaN(q)){
t.val('+7 (');
}
else{
t.val('+7 ('+q);
}
}
else if(l===7){
t.val(v+')');
}
else if(l===9){
t.val(v1+' '+q);
}
else if(l===13||l===16){
t.val(v1+'-'+q);
}
else if(l>18){
v=v.substr(0,18);
t.val(v);
}
}
else{
if(l<4){
t.val('+7 ');
}
}
},100);
}
}
I was developed simple and easy masks on input field to US phone format jquery-input-mask-phone-number
Simple Add jquery-input-mask-phone-number plugin in to your HTML file and call usPhoneFormat method.
$(document).ready(function () {
$('#yourphone').usPhoneFormat({
format: '(xxx) xxx-xxxx',
});
});
Working JSFiddle Link https://jsfiddle.net/1kbat1nb/
NPM Reference URL https://www.npmjs.com/package/jquery-input-mask-phone-number
GitHub Reference URL https://github.com/rajaramtt/jquery-input-mask-phone-number
If you don't want to show your mask as placeholder you should use jQuery Mask Plugin.
The cleanest way:
var options = {
onKeyPress: function(phone, e, field, options) {
var masks = ['(00) 0000-00000', '(00) 00000-0000'];
var mask = (phone.length>14) ? masks[1] : masks[0];
$('.phone-input').mask(mask, options);
}
};
$('.phone-input').mask('(00) 0000-00000', options);
Yes use this
$("#phone").inputmask({"mask": "(99) 9999 - 9999"});
Link here
$('.phone').focus(function(e) {
// add mask
$('.phone')
.mask("(99) 99999999?9")
.focusin(function(event)
{
$(this).unmask();
$(this).mask("(99) 99999999?9");
})
.focusout(function(event)
{
var phone, element;
element = $(this);
phone = element.val().replace(/\D/g, '');
element.unmask();
if (phone.length > 10) {
element.mask("(99) 99999-999?9");
} else {
element.mask("(99) 9999-9999?9");
}
}
);
});

How to reset only the Input on the Alert Box in Javascript?

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 = "";
}

Categories

Resources