i am trying to build a calculator but in that i am unable to perform sum operation besides it concatenation is occurred how i can do this sum, also how to empty the text box when entering new value in the text-box after pressing '=' my code is this
<title>Calculator</title>
<script>
var v = 0 ;
var operator = '';
function calc(obj){
if (obj.value == '+' || obj.value == '-' || obj.value == '*' || obj.value == '/' ){
v = document.getElementById("text_field").value;
operator = obj.value;
document.getElementById("text_field").value = '';
}
else if (obj.value == '='){
if (operator == '+')
{
document.getElementById("text_field"). value = v + document.getElementById("text_field").value ;
}
if (operator == '-')
{
document.getElementById("text_field").value = v - document.getElementById("text_field").value ;
}
if (operator == '*')
{
document.getElementById("text_field").value =v * document.getElementById("text_field").value ;
}
if (operator == '/')
{
document.getElementById("text_field").value = v / document.getElementById("text_field").value ;
}
}
else {
document.getElementById("text_field").value = document.getElementById("text_field").value + obj.value;
}
}
</script>
Use parseInt: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
for example:
parseInt(document.getElementById("text_field").value)
Related
I'm trying to create a calculator program for my assignment course in JavaScript. The program has to calculate to numbers (values assigned by the user), as well as the operator (+, - , * ,/), and to display the result.
If the user input an extra character in the field like (15n + 20 or 15 ++ 20 or 15+ + 20) has to display an error "Cannot concatenate a number with a string"
if the user divide a number by 0 has to display "Division by 0 is not allowed"
Please I really need your help.
I posted, my code bellow, let me know. What I'm doing wrong?
I want to mention that I'm at the beginning level.
Thanks, I appreciate all the advices
let numberOne = parseFloat(prompt("First Number: "));
let operator = prompt("Chose operation (+ - * /): ");
let numberTwo = parseFloat(prompt("Second Number: " ));
function DivisionByZero(a, b) {
if (a == 0 || b == 0 == true) {
throw "Divizion by 0 is not allowed";
}
}
function TypingError(a, b, c) {
if (numberOne + " " == true) {
throw "Cannot concatenate a number with a string";
} else if (numberTwo + " " == true) {
throw "Cannot concatenate a number with a string";
} else if (operator + operator == true) {
throw "Can not concatenate two operators"
}
}
let TypingErrorDisplay = TypingError(numberOne, operator, numberTwo);
var ErrorDivisionDisplay = DivisionByZero(numberOne, numberTwo);
if (operator === "+") {
var calc = parseFloat(numberOne) + parseFloat(numberTwo);
alert(calc);
}
else if (operator === "-") {
var calc = parseFloat(numberOne) - parseFloat(numberTwo);
alert(calc);
}
else if (operator === "*") {
var calc = parseFloat(numberOne) * parseFloat(numberTwo);
alert(calc);
}
else if (operator === "/") {
var calc = parseFloat(numberOne) / parseFloat(numberTwo);
alert(calc);
if (ErrorDivisionDisplay == true) {
alert("Division by 0 is not allowed");
}
}
else {
alert(TypingErrorDisplay);
}
First of all,
in your first condition you have
function DivisionByZero(a, b) {
if (a == 0 || b == 0 == true) {
throw "Divizion by 0 is not allowed";
}
}
You can't have b == 0 == true.
You just need :
function DivisionByZero(a, b) {
if (a === 0 || b === 0) {
throw "Divizion by 0 is not allowed";
}
}
for the rest, you should check that post : Check if a variable is a string in JavaScript
function TypingError(a, b, c) {
if (typeOf(numberOne) == "string") {
throw "Cannot concatenate a number with a string";
}
else if (typeOf(numberTwo) === "string") {
throw "Cannot concatenate a number with a string";
}
else if (operator.lenght > 1) {
throw "Can not concatenate two operators"
}
}
Try to correct that things fisrt and tell us.
Axel,
let numberOne = parseFloat(prompt("First Number: "));
let operator = prompt("Chose operation (+ - * /): ");
let numberTwo = parseFloat(prompt("Second Number: " ));
function DivisionByZero(a, b) {
if (a == 0 || b == 0) { // You don't need == true, you already declared the conditions
throw "Divizion by 0 is not allowed";
}
}
function TypingError(n1, op, n2) {
if (!n1.isFinite()) { // Triggers if numberOne is not finite
throw "Cannot concatenate a number with a string";
} else if (!n2.isFinite()) { // Triggers if numberTwo is not finite
throw "Cannot concatenate a number with a string";
} else if (op != "+" && op != "-" && op != "*" && op != "/") { // Accept only valid arithmetic operators
throw "Can not concatenate two operators"
}
}
let TypingErrorDisplay = TypingError(numberOne, operator, numberTwo);
var ErrorDivisionDisplay = DivisionByZero(numberOne, numberTwo);
if (operator === "+") {
var calc = parseFloat(numberOne) + parseFloat(numberTwo);
alert(calc);
}
else if (operator === "-") {
var calc = parseFloat(numberOne) - parseFloat(numberTwo);
alert(calc);
}
else if (operator === "*") {
var calc = parseFloat(numberOne) * parseFloat(numberTwo);
alert(calc);
}
else if (operator === "/") {
var calc = parseFloat(numberOne) / parseFloat(numberTwo);
alert(calc);
if (ErrorDivisionDisplay == true) {
alert("Division by 0 is not allowed");
}
}
else {
alert(TypingErrorDisplay);
}
#Solution#
The solution that I found it is displayed below. Please let me know what you think about it.
let numberOne = prompt("First Number: ");
let operator = prompt("Chose operation (+ - * /): ");
let numberTwo = prompt("Second Number: ");
function TypingError(op1, op2, operation) {
if (isNaN(numberOne) || numberOne.length == 0 || isNaN(numberTwo) || numberTwo.length == 0) {
return -1;
}
if (operation !== undefined && operation.length > 1) {
return -2;
}
return 0;
}
let TypingErrorDisplay = TypingError(numberOne, numberTwo, operator);
if (TypingErrorDisplay == -1) {
alert("one of the operands is not numeric ");
}
else if (TypingErrorDisplay == -2) {
alert("wrong operation - symbol must have one character");
}
else {
numberOne = parseFloat(numberOne);
numberTwo = parseFloat(numberTwo);
if (operator == "+") {
var calc = numberOne + numberTwo;
alert(calc);
}
else if (operator == "-") {
var calc = numberOne - numberTwo;
alert(calc);
}
else if (operator == "*") {
var calc = numberOne * numberTwo;
alert(calc);
}
else if (operator === "/") {
if (numberTwo == 0) {
alert("Division by 0 is not allowed");
}
else {
var calc = numberOne / numberTwo;;
alert(calc);
}
}
else {
alert("operation " + operator + " not exists");
}
}
I'm making a puzzle game where the user uses WASD to move a character up, left, down, right respectively. It works fine at the moment but I was wondering if there was a way to break the code down into more intuitive functions. Below is my code:
function move(e)
{
for (var y = 0; y < mapHeight; y++) {
for (var x = 0; x < mapWidth; x++) {
if (map[y][x] == "#" || map[y][x] == "+") {
break;
}
}
if (map[y][x] == "#" || map[y][x] == "+") {
break;
}
}
var player_x = x;
var player_y = y;
if (e.key == 'w') {
var player_new_x = player_x;
var player_new_y = player_y - 1;
if (moveBox(player_new_x, player_new_y, "up") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else if (e.key == 's') {
var player_new_x = player_x;
var player_new_y = player_y + 1;
if (moveBox(player_new_x, player_new_y, "down") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else if (e.key == 'a') {
var player_new_x = player_x - 1;
var player_new_y = player_y;
if (moveBox(player_new_x, player_new_y, "left") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else if (e.key == 'd') {
var player_new_x = player_x + 1;
var player_new_y = player_y;
if (moveBox(player_new_x, player_new_y, "right") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else {
return;
}
render();
}
Is it possible to make four functions, one for each of the movement keys? Any help would be much appreciated
Yes
It´s possible to do what you want, 4 different functions
But ... you should intercept the events keydown (when the user presses the key) and keyup (when the user releases the key)
As long as the key is "pressed" you do the movement
You can create an object like this
let move = { moveH : 0 , moveV :0 }
When the keydown event is detected for "a" -> {moveH : -1, moveV :0}
"s" -> { moveH :0 , moveV :1 }
"w" -> { moveH :0 , moveV :-1 }
"d" -> { moveH :1 , moveV :0 }
When the keyup event is detected .. for any key -> {moveH :0 , moveV:0 }
Meanwhile
apply the move to the object on the screen
something like
stuff.position = { x : stuff.position.x + move.moveH , y: stuff.position.y + move.moveV }
I am trying to write a function that will validate that all entries within the commas are numberic and display "?" if they are not. for example: user enters 2,3,5b,c7 the output that I am getting is BCE? instead of BC?? This is the decode function that I am trying to validate in:
function fnDecode() {
var msg = $("textin").value;
if(msg === "") {
$("textin_span").innerHTML = "* Please enter a value to decode
*";
$("textin").focus();
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(","); //split method separates by delimiter
var outstr = ""; //out string
for (var i=0; i<nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) { //if isNaN true, print ?
outstr += "?";
} else if (isNallN(nums[i])) { //THIS IS WHERE THE FN GOES
outstr += "?";
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 >26) {
outstr += "?";
}else {
outstr += String.fromCharCode(n2+64);
}
}
$("textout").value = outstr;
}
function isNallN(s) {
}
I corrected your fnDecode function.
You don't need multiple if to check for isNaN, !isNaN('5') will work as well as !isNaN(5). Check this Javascript Equality Table for more information.
Here, I adapted the function for it to work with a String given in
parameter and to return the wanted String.
function fnDecode(msg) {
var nums = msg.split(",");
var outstr = "";
for (num of nums) {
if (isNaN(num)) outstr += "?"; //isNaN works on "5" and 5
else if (+num === 0) outstr += " "; //We use +num to parse the String to an int
else if (+num < 1 || +num > 26) outstr += "?";
else outstr += String.fromCharCode(+num + 64);
}
return outstr;
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a shorter ES6 version :
function fnDecode(msg) {
return msg.split(',').map( num => isNaN(num) || (+num < 1 || +num > 26) ? '?' : +num == 0 ? ' ' : String.fromCharCode(+num + 64)).join('');
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
I want to make user control to get number like this:
125.00
125
125.27
125.20
1231545.25
2566.66
I have tried with mask textbox but its length can be anything.
I have used textbox with Javascript that accepts a number
like this:
click here
If a Javascript plugin is available for this let me know,
or any code to accept value in price format.
Restrict user to insert only number and two decimal spaces while entering.
If number is not well formatted then cut and format number after text change.
Like if 125.2 then 125.20 or if 125 then 125.00 or 135156. then 135156
I have search on internet but no plugin or script was found for this.
I have a plugin like numeric.js but it doesn't restrict decimal spaces.
Post if any Javascript available.
I don't want to do validation to check for entered values; I want to accept values with restriction.
Please help me.
You can use Ajax Control Toolkit MaskedEdit control:
MaskedEdit is an ASP.NET AJAX extender that attaches to a TextBox control to restrict the kind of text that can be entered. MaskedEdit applies a "mask" to the input that permits only certain types of characters/text to be entered. The supported data formats are: Number, Date, Time, and DateTime. MaskedEdit uses the culture settings specified in the CultureName property. If none is specified the culture setting will be the same as the page: English (United States).
Sample Code:
<ajaxToolkit:MaskedEditExtender
TargetControlID="TextBox2"
Mask="9,999,999.99"
MessageValidatorTip="true"
OnFocusCssClass="MaskedEditFocus"
OnInvalidCssClass="MaskedEditError"
MaskType="Number"
InputDirection="RightToLeft"
AcceptNegative="Left"
DisplayMoney="Left"
ErrorTooltipEnabled="True"/>
See Working Demo
I also having same problem.This code has solved my problem.This solution is exactly what u want.It's not only foramt yous decimal number but also will eliminate blank spaces. Try this.As in my condition i was allowing user to enter '+' or '-' so i check for this validation also.
<script type="text/javascript">
function checkforvalidation() {
var txtvalue = document.getElementById('<%=txtspherical.ClientID %>').value;
var leftstr = "";
var rightstr = "";
var tempstr = "";
var operator = "";
txtvalue = txtvalue.replace(/\s/g, '');
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
if (txtvalue.indexOf(".") != -1) {
leftstr = txtvalue.split(".")[0];
rightstr = txtvalue.split(".")[1];
if (leftstr.indexOf("-") == 0 || leftstr.indexOf("+") == 0) {
operator = leftstr.substr(0, 1);
tempstr = leftstr.substr(1, leftstr.length - 1);
leftstr = ltrim(tempstr, '0');
if (leftstr.length == 0) {
leftstr = '0';
}
if (rightstr.indexOf("-") == -1 || rightstr.indexOf("+") == -1) {
rightstr = ltrim(rightstr, '0');
rightstr = chkdecimalpoints(rightstr);
if (operator != null || operator != "") {
txtvalue = operator + leftstr + "." + rightstr;
}
else {
txtvalue = leftstr + "." + rightstr;
}
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
else {
document.getElementById('<%=txtspherical.ClientID %>').value = "";
}
}
else {
tempstr = leftstr.substr(0, leftstr.length);
leftstr = ltrim(tempstr, '0');
if (leftstr.length == 0) {
leftstr = '0';
}
if (rightstr.indexOf("-") == -1 || rightstr.indexOf("+") == -1) {
rightstr = rtrim(rightstr, '0');
rightstr = chkdecimalpoints(rightstr);
txtvalue = leftstr + "." + rightstr;
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
}
}
else if (txtvalue.indexOf("-") == -1 || txtvalue.indexOf("+") == -1) {
txtvalue = ltrim(txtvalue, '0');
if (txtvalue.length == 0) {
txtvalue = '0';
}
if (operator != null || operator != "") {
txtvalue = operator + txtvalue + ".00";
}
// txtvalue = leftstr + "." + rightstr;
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
else if (txtvalue.indexOf("-") == 0 || txtvalue.indexOf("+") == 0) {
operator = txtvalue.substr(0, 1);
tempstr = txtvalue.substr(1, leftstr.length - 1);
txtvalue = alltrim(tempstr, '0');
if (operator != null || operator != "") {
txtvalue = operator + txtvalue + ".00";
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
}
}
function chkdecimalpoints(rightstr) {
if (rightstr.length == 0) {
rightstr = '00';
return rightstr;
}
else if (rightstr.length == 1) {
rightstr = rightstr + '0';
return rightstr;
}
else if (rightstr.length > 2) {
var tempvar = rightstr.substr(2, 1);
if (tempvar >= 5) {
tempvar = parseInt(rightstr.substr(1, 1)) + 1;
tempvar = rightstr.substr(0, 1) + tempvar.toString();
if (tempvar.length > 2) {
tempvar = tempvar.substr(0, 2);
}
return tempvar;
}
else {
tempvar = rightstr.substr(0, 2);
return tempvar;
}
}
else {
return rightstr;
}
}
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function alltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+$", "g"), "");
}
</script>
HTML Source:
<asp:TextBox ID="txtspherical" runat="server" OnBlur="javascript:checkforvalidation();">
</asp:TextBox>
function validNumber(input){
input=input.replace(/\s+/g," ").replace(/^\s+|\s+$/g,"");
if( input.match(/\d+\.*\d*/i) ){
input=input.match(/(\d+\.*\d*)/i)[1].replace(/\.$/i, "");
if(!input.match(/\./i)) input+=".00";
if(input.match(/\.(\d+)/i)[1].length<2) input+="0";
return input;
}else{
return "0.00";
}
}
See the bottom of this post;
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(aString)
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);
You iterate on sString wich doesn't exist and not on your parameter aString.
Where is sString being declared in your function? Try with aString (or declare var sString = aString) and try again.
Please change function myF(aString) to function myF(sString)
There is a naming mistake. Here is a working copy of your code .
http://jsfiddle.net/hXarY/
You can try using "firebug" to catch such errors if you do not already do.
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(sString) // this should be sString , not aString
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);