Division by zero checking - javascript

Doing my calculator...Want to check if my input str has "0" and if it is to alert error. But how not to check "/"? Here it is my function:
<input type="text" name="answer" id="t" onkeyup="isAllowedSymbol(this);checkLength(this);" placeholder="Enter data" >
<input type="button" value=" ÷ " onclick="calculator.answer.value += '/';div(this);checkLength(this);" />
function div(input)
{
var input = document.getElementById("t");
var lastElement = (input.value.length-1);
//alert(input.value.charAt(lastElement));
if (input.value.charAt(lastElement) == 'null')
{
alert(" / to Zero");
}
}

You can use parseInt to evaluate the value of a string.
if (parseInt($("#myInput").val()) > 0) {
// Do something...
}
You can also detect division by zero by using isFinite:
if (isFinite(1/0)) {
// This won't run
} else {
...
}
isFinite will also return false for NaN:
if (isFinite(NaN)) {
// This won't run
} else {
...
}

Instead of using
input.value.charAt(lastElement) == 'null'
in your if statement use
input.value[lastElement-1]+input.value[lastElement] === "/0"
This will check if the last section of the string is zero right after the / sign.
function div(input)
{
var input = document.getElementById("t");
var lastElement = (input.value.length-1);
if (input.value[lastElement-1]+input.value[lastElement] === "/0")
{
alert(" / to Zero");
}
}
<input type="text" name="answer" id="t" placeholder="Enter data" >
<input type="button" value=" ÷ " onclick="div(this);" />

May be it is not full answer but what you can say about this one?
function div(input)
{
var input = document.getElementById("t");
var lastElement = (input.value.length-1);
//alert(input.value[lastElement-1]);
//alert(input.value[lastElement]);
if (input.value[lastElement-1] === "/")
{
if (input.value[lastElement] === "0")
{
alert(" / to Zero");
}
}
}

Related

While Loop Input Issue

I am trying to make a program that takes numbers from the user until they input a 0, the output how many positive and negative numbers were input, while also telling the user whether the number they input was positive, negative, or zero, however, when I use it, it crashes the webpage immediately if anything but a 0 is input. So I was wondering where this issue would be coming from and how I could resolve it.
JS:
var pos = 0;
var neg = 0;
var inp = 1;
function interpreter() {
while (inp != 0) {
inp = (document.getElementById("number"));
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML = pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML = neg + " negative numbers were inputted";
}
}
}
Where "number" is a text field for input, and the function is called upon the press of a button. Thanks in advance!
You're misunderstanding the event-processing nature of JavaScript.
If you have a while loop like that, you'll never yield control back to the browser itself, to handle user input, etc. You may be looking for something like this -- in addition to the removal of the explicit loop, note how the handling of inp has changed; previously you were comparing strings to numbers.
var pos = 0;
var neg = 0;
function interpret() {
var inp = parseInt(document.getElementById("number").value);
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML =
pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML =
neg + " negative numbers were inputted";
}
}
<form onsubmit="interpret();event.preventDefault()">
<input id="number">
<input type="submit" value="Interpret value">
</form>
<div id="output1"></div>
<div id="output2"></div>
<div id="output3"></div>
If you really want my suggest:
var pos = 0
, neg = 0
;
document.forms['my-form'].addEventListener('submit',function(evt)
{
evt.preventDefault()
let inp = this.number.valueAsNumber
{
if (inp < 0)
{
this.out_1.textContent = 'Input is: negative'
neg++
}
else if (inp > 0)
{
this.out_1.textContent = 'Input is: positive'
pos++
}
else
{
this.out_1.textContent = 'Input is: zero';
this.out_2.textContent = pos + ' positive numbers were inputted'
this.out_3.textContent = neg + ' negative numbers were inputted'
}
}
})
label, button, output { display: block; margin:.4em; }
<form name="my-form">
<label>
Input:
<input name="number" type="number" min="-32768" max="32768" value="1">
</label>
<button type="submit"> enter </button>
<output name="out_1"></output>
<output name="out_2"></output>
<output name="out_3"></output>
</form>

how to print based on value entered

so If I entered 10, number 10 should be printed ten times
function function_name(number) {
for (var counter = 1; counter <= number; counter++) {
document.write("the number is" + number);
}
}
<label for="number">Enter number: </label>
<input name="number" id="number" />
Looks like you just need to:
Add a button to your HTML
Add a click handler to your button that will activate your function
function writeTimes(number) {
for (var counter = 1; counter <= number; counter++) {
document.write("the number is" + number);
}
}
function doTheThing() {
var input = document.getElementById("my-input"); //get the input element
var numberOfTimes = input.value; //get the number of times
writeTimes( numberOfTimes ); //call your function
}
<label for="number">Enter number: </label>
<input id="my-input" name="number" id="number" />
<button onclick="doTheThing()">Go</button>
// This function *does* something. Give it a name that reflects it's behavior.
// You can always rename it later if you change what it does.
//
function spamNumber(number) {
// Use let instead of var, it's replacement for var with less wtf behavior
//
for (let counter = 1; counter <= number; counter++) {
// I don't care for document.write. It's totally unusable in production code.
// But sure, why not? At least add a line break so the outputs
// don't smush together.
//
document.write("the number is " + number + '<br/>');
}
}
// Find the input element so we can add a listener
//
document.querySelector('input')
// Listening in this case only to keydowns that occur while input has focus.
//
.addEventListener('keydown', function onKeydown(evt) {
if (event.key === 'Enter') {
// evt.target is the input element, number in it's value property.
// Force value to integer in case someone inputs garbage. We can
// fail silently and move on.
//
spamNumber( parseInt(evt.target.value) || 0)
}
})
// Now type in your number and press Enter
<label for="number">Enter number: </label>
<input name="number" id="number" />
From your question and comments , i think you are looking for this:
onload = function (){
var result = document.getElementById('result');
var number = document.getElementById('number');
number.oninput = function (){
if(number.value == "0" || number.value.length == ""){result.innerHTML="";}else{}
var counter = "";
var repeat =number.value;
while (repeat > 0) {
repeat--;
var str =" (the number is " + parseInt(number.value)+" )";
result.innerHTML= str.repeat(number.value);
}
return counter;
number.onpropertychange = number.oninput;
number.onchange = number.oninput;
}};
<label for="number">Enter number: </label>
<input name="number" id="number" /><br />
<span id=result></span>

Why it gives me String every time?

I got input from input tags but whatever I write in inputs it recognize as string value so that I can't use my conditions.
and the second problem if I enter "ddd" for first input and "111" for second input and press button it shows NaN in console. I want to show alert instead of this. How can I correct these?
function addFunc() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
if (typeof x == 'string' || typeof y == 'string') {
var result = parseInt(x) + parseInt(y);
console.log(result);
} else {
alert("Wrong Entry!");
}
}
<input id="num1">
<input id="num2">
<button type="button" onclick="addFunc()">ADD</button>
<p id="result"></p>
The value of an input field will always be a string. Try using isNaN() to determine if the decimal parsed correctly:
function addFunc() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>
Alternatively, if you want to eliminate all bad input (1e would be invalid), try using a + symbol before the string value to convert it to a number. If the string can't be converted, it will return NaN:
function addFunc() {
var x = +document.getElementById("num1").value;
var y = +document.getElementById("num2").value;
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>

Javascript won't calculate

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>

How to check number being entered in textbox dynamically?

i have 5 textbox like
<input type ="text" size="3" name="r"><br>
<input type ="text" size="3" id="1" onchange="vali(this.id)" name="I"><br>
<input type ="text" size="3" name="a"><br>
<input type ="text" size="3" name="s"><br>
<input type ="text" size="3" name="e">
function vali(d){
if(document.getElementById(d).value <0 || document.getElementById(d).value >=30)}
I want user should enter only max 2 digits on each field between 0 & 30. I'm not able to restrict user to enter only 2 digits in field, for example when user enters 151, 15 should come on 1st field and then focus will go on 2nd field automatically and remaining digits will be entered in 2nd field and will be there till the user enters another digit. After entering focus will come on field 3 like this. Also I need to check to each field contain a number between 0 and 30 which I'm checking in above code.
Also when user submit the form all field should be checked for value between (0 to 30) If there is any field present alert bos should pop up else go to next page.i m not able to do this part .this is my form part above the 5 input field
<form name="detail" action ="selectjzone.jsp" onsubmit="return validate(this)">
and edited part is
if (num < 0) {
alert("The value enteres for " +" " + document.getElementById(obj.id).name + " " + "is outside the range0 to 30" );
return false;
} else if (num > 30) {
alert("The value enteres for " +" " + document.getElementById(obj.id).name + " "+ "is outside the range0 to 30" );
return false;
}
return true;
}
Here's a start at how to validate the field and move any extra to the next field:
Working demo here: http://jsfiddle.net/jfriend00/vpTq5/
HTML:
<input id="a" type ="text" size="3" onkeyup="validate(this, 'b')" name="r"><br>
<input id="b" type ="text" size="3" onkeyup="validate(this, 'c')" name="I"><br>
<input id="c" type ="text" size="3" onkeyup="validate(this, 'd')" name="a"><br>
<input id="d" type ="text" size="3" onkeyup="validate(this, 'e')" name="s"><br>
<input id="e" type ="text" size="3" onkeyup="validate(this)" name="e">
Javascript:
function validate(obj, next) {
// fetch value and remove any non-digits
// you could write more code to prevent typing of non-digits
var orig = obj.value;
var mod = orig.replace(/\D/g, "");
var nextObj;
// check length and put excess in next field
if (mod.length > 2) {
// shorten the current value
obj.value = mod.substring(0,2);
if (next) {
// put leftover into following value
var nextObj = document.getElementById(next);
if (!nextObj.value) {
nextObj.value = mod.substring(2);
nextObj.focus();
}
}
} else {
// only set this if necessary to prevent losing cursor position
if (orig != mod) {
obj.value = mod;
}
}
// convert to number and check value of the number
var num = Number(obj.value);
// don't know what you want to do here if the two digit value is out of range
if (num < 0) {
obj.value = "0";
} else if (num > 30) {
obj.value = "30";
}
}
Some notes:
Id values on HTML objects cannot start with a digit. They must start with a letter.
You will have to decide what behavior you want when a number greater than 30 is entered.
Keep in mind that input field values are strings. If you want to treat them like a number, you have to convert them to be numeric.
With more code, you can actually prevent the typing of non-numeric keys and you can move the focus before the 3rd value is typed.
There are ways to get data into fields that does not trigger onkeyup (copy/paste, drag/drop) so you will have to validate at other times too.
If you can use a framework like jQuery, this can be done in a simpler way.
Here is the code for automatic focusing on next field when you keep on typing,
you need to take of validating number between 0 & 30. Hope this helps,
<script>
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function chkEvent(e){
var keyCode = (isNN) ? e.which : e.keyCode;
if(e.shiftKey==1 && keyCode == 9) return false;
if(e.shiftKey==1 || keyCode == 9 || keyCode == 16) return false;
return true;
}
function autoTab(current,to, e) {
var keyCode = (isNN) ? e.which : e.keyCode;
var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
if(current.getAttribute && current.value.length == current.getAttribute("maxlength") && !containsElement(filter,keyCode)) to.focus();
function containsElement(arr, ele) {
var found = false, index = 0;
while(!found && index < arr.length) if(arr[index] == ele) found = true; else index++;
return found;
}
return true;
}
</script>
<input type ="text" size="3" maxlength="2" name="r" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('1'), event);}"><br>
<input type ="text" size="3" maxlength="2" id="1" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('a'), event);}" name="I"><br>
<input type ="text" size="3" maxlength="2" id="a" name="a" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('s'), event);}"><br>
<input type ="text" size="3" maxlength="2" id="s" name="s" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('e'), event);}"><br>
<input type ="text" size="3" maxlength="2" id="e" name="e" >
Here is pure javascript solution is it like what you wanted at all?
http://jsfiddle.net/rfyC8/
Code:
var ieEvents = !!document.attachEvent,
addEvent = ieEvents ? "attachEvent" : "addEventListener",
keyUp = ieEvents ? "onkeyup" : "keyup";
function validator( e ) {
var sib, intValue, val = this.value;
if( val.length >= 2 ) {
intValue = parseInt( val, 10 );
if( isNaN( intValue ) || intValue < 0 || intValue > 30 ) {
this.value = "";
return false;
}
sib = this.nextSibling;
while( sib && sib.className != "textfield" ) {
sib = sib.nextSibling;
}
if( sib ) {
sib.focus();
}
else {
return false;
}
}
}
document.getElementById("textfields")[addEvent]( keyUp,
function(){
var e = arguments[0] || window.event,
target = e.target || e.srcElement;
if( target.className == "textfield" ) {
validator.call( target, e );
}
},
false
);
Use maxlength attribute to limit number of input
maxlength="2"
After settting the above you can use onkeyup event to check the length and change focus
$('#target').keyup(function () {
var maxlength = $(this).attr('maxlength');
if ($(this).val().trim().length == maxlength){
//change focus to next input
//change focus to next input
var inputs = $(this).closest('form').find(':input');
inputs.eq(inputs.index(this) + 1).focus();
}
});

Categories

Resources