How to make this IF statement work - javascript

Ok, I'm trying to have the code run so people enter an amount of money and then it shows an estimate of how much they make daily. I want it to have an ERROR pop up if the textbox has no numbers in it. How should I do this?
This is my current code:
<!DOCTYPE html>
<html>
<head>
<title> MoneyPerYear </title>
<link type="text/css" rel="stylesheet" href="money.css">
</head>
<body>
<p id="header"> Enter yearly income to estimate daily earnings </p>
<input type="text" id="textmoney">
<div onclick="moneyFunction()" id="moneydiv"> <p id="divtext">Calculate</p> </div>
<p id="demo"></p>
<script>
function moneyFunction() {
var money = document.getElementById('textmoney').value;
var dailyE = money/365;
document.getElementById('demo').innerHTML = (dailyE);
}
if ( document.getElementById('textmoney').value; == 0) {
document.getElementById('demo').innerHTML = "ERROR";
}
</script>
</body>
</html>

So here is all of it:
<!DOCTYPE html>
<html>
<head>
<title> MoneyPerYear </title>
<link type="text/css" rel="stylesheet" href="money.css">
</head>
<body>
<p id="header"> Enter yearly income to estimate daily earnings </p>
<input type="text" id="textmoney">
<button onclick="moneyFunction()" id="moneydiv"> <p id="divtext">Calculate</p> </button>
<p id="demo"></p>
<script>
function moneyFunction() {
var money = document.getElementById('textmoney').value;
if ( document.getElementById('textmoney').value == 0) {
alert("Error");
}
var dailyE = money/365;
document.getElementById('demo').innerHTML = (dailyE);
}
</script>
</body>
</html>

function moneyFunction() {
var money = +(document.getElementById('textmoney').value) || 0; //parse required
var dailyE = money / 365;
//var result = money === 0 ? 'ERROR' : dailyE;
var result = money === 0 ? 'ERROR' : parseFloat(dailyE).toFixed(3); //round-off
document.getElementById('demo').innerHTML = result;
} //closing bracket
#moneydiv {
border: 1px solid grey;
padding: 5px;
background: skyblue;
display: inline-block;
cursor: pointer;
}
<p id="header">Enter yearly income to estimate daily earnings</p>
<input type="text" id="textmoney">
<div onclick="moneyFunction()" id="moneydiv">
<p id="divtext">Calculate</p>
</div>
<p id="demo"></p>

Related

I have a problem with JavaScript onClick function

I have started doing a game, kinda similar to 'Spend Bill Gates Money', but I've said to change it up a bit.
I've done the first item, and I've tried to edit it with JS, so everytime you press "Buy", it will remove 1 dollar from you, or, when you press "Sell" to give you 1 dollar. The problem is, everytime I click, it only counts once. Plus, if I press "Buy", then "Sell", it gives me instantly 11 dollars, instead of 10 dollars.
Filename: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width = device-width, initial-scale = 1.0">
<link href="https://fonts.googleapis.com/css?family=Roboto+Slab&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>Spend you own money</title>
<script src="script.js">
</script>
<link rel="stylesheet" href="style.css">
<body>
<noscript>You need to enable javascript in order to have fun!</noscript>
<h1 class="center" id = "money">Money Left: 10</h1><!--Money = 100 000 000 000-->
<div class= "main">
<div class="pen">
<h2>Pen</h2>
<input type="submit" class="sell" value="Sell" onclick="sellpen()">
<!-- <input type="text" class="amount" value = 0 id = "amountpen" readonly="readonly" size="9%"> -->
<input type="submit" class="buy" value="Buy" onclick="amountpen()" >
</div>
</div>
</body>
</head>
</html>
Filename: script.js
var money = 10; //dollars
var pen = 1; // dollar
var mpen = money-pen;
var ppen = money+pen;
function amountpen() {
document.getElementById("money").innerHTML = "Money Left: " + mpen;
money = money-1;
}
function sellpen() {
document.getElementById("money").innerHTML = "Money Left: " +ppen;
money = money+
Your script.js would be like this:
var money = 10;
var pen = 1;
function amountpen() {
var mpen = money-pen;
document.getElementById("money").innerHTML = "Money Left: " + mpen;
money = money-1;
}
function sellpen() {
var ppen = money+pen;
document.getElementById("money").innerHTML = "Money Left: " +ppen;
money = money+1;
}
You can try with this JS code :
money = 10; //dollars
function amountpen() {
money--;
document.getElementById("money").innerHTML = "Money Left: " + money;
}
function sellpen() {
money++;
document.getElementById("money").innerHTML = "Money Left: " +money;
}

Add two text fields together that include commas and decimals with JavaScript only

In order to add a feature to a existing application I'm attempting to use JavaScript to add together input fields which need to stay as text field types and show the end result text field as a total of those fields. I can easily make it work adding the numbers together. However the numbers will be typed in with commas and decimals every time. When this happens the adding breaks and doesn't work. Anyone have any ideas of how I could possibly make this work?
HTML CODE
<form method="post">
<input type="text" id="the_input_id">
<input type="text" id="the_input_id1">
<input type="text" id="total">
JavaScript
$(function() {
$('#the_input_id').keyup(function() {
updateTotal();
});
$('#the_input_id1').keyup(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('#the_input_id').val());
var input2 = parseInt($('#the_input_id1').val());
if (isNaN(input1) || isNaN(input2)) {
if(!input2){
$('#total').val($('#the_input_id').val());
}
if(!input1){
$('#total').val($('#the_input_id1').val());
}
} else {
$('#total').val(input1 + input2);
}
};
var output_total = $('#total');
var total = input1 + input2;
output_total.val(total);
});
How about something like this?
var num1 = "1,000,000.00"
var num2 = "1,000,000.25"
var re = /,/gi;
var num1a = num1.replace(re,''); // strip commas
var num2a = num2.replace(re, ''); // strip commas
var sum = Number(num1a) + Number(num2a); // convert to Number and add together
console.log(sum); // before formatting
var total = Number(sum).toLocaleString(); // formatted
console.log(total)
Read my comment above, then take a look here:
//<![CDATA[
/* js/external.js */
$(function(){
var num1 = $('#num1'), num2 = $('#num2'), total = $('#total'); // why get them again unless they're dynamic ?
function updateTotal(){
var s = num1.val().replace(/,/g, ''), s2 = num2.val().replace(/,/g, '');
if(s === '' && s2 === ''){
total.text('Awaiting Input').addClass('er');
}
else if(isNaN(s) && isNaN(s2)){
total.text('Numbers Required').addClass('er');
}
else if(s === ''){
total.text('Awaiting First Number').addClass('er');
}
else if(isNaN(s)){
total.text('First Input Requires Number').addClass('er');
}
else if(s2 === ''){
total.text('Awaiting Second Number').addClass('er')
}
else if(isNaN(s2)){
total.text('Second Input Requires Number').addClass('er');
}
else{
total.text(((+s)+(+s2)).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2})).removeClass('er');
}
};
num1.keyup(updateTotal); num2.keyup(updateTotal);
}); // end jQuery load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px;
}
input[type=text]{
width:100px; padding:0 3px;
}
.er{
color:#900;
}
#total{
display:inline-block;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='content'>
<input type='text' id='num1' /> &plus;
<input type='text' id='num2' /> &equals;
<div class='er' id='total'>Awaiting Input</div>
</div>
</body>
</html>
Note that you can use + in front of a String to cast it to a number... and that JavaScript has a Floating Point Number Math issue.
Here is a <form> example:
//<![CDATA[
/* js/external.js */
$(function(){
var form = $('#form'), num1 = $('#num1'), num2 = $('#num2'), total = $('#total'); // why get them again unless they're dynamic ?
function updateTotal(){
var s = num1.val().replace(/,/g, ''), s2 = num2.val().replace(/,/g, '');
if(s === '' && s2 === ''){
total.val('Awaiting Input').addClass('er');
}
else if(isNaN(s) && isNaN(s2)){
total.val('Numbers Required').addClass('er');
}
else if(s === ''){
total.val('Awaiting First Number').addClass('er');
}
else if(isNaN(s)){
total.val('First Input Requires Number').addClass('er');
}
else if(s2 === ''){
total.val('Awaiting Second Number').addClass('er')
}
else if(isNaN(s2)){
total.val('Second Input Requires Number').addClass('er');
}
else{
total.val(((+s)+(+s2)).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2})).removeClass('er');
}
};
form.submit(function(e){
console.log(form.serialize());
// run a bunch of tests using if conditions and the like before AJAXing - $.post example shown
/*
$.post('sendToPage.php', form.serialize(), function(jsonResult){
// should get echo json_encode($objOrAssocArray); from PHP as jsonResult now
}, 'json');
*/
// prevents old school submission
e.preventDefault();
});
num1.keyup(updateTotal); num2.keyup(updateTotal);
}); // end jQuery load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px;
}
input[type=text]{
width:100px; padding:3px 5px;
}
.symbol{
display:inline-block; width:18px; text-align:center;
}
.er{
color:#900;
}
#total{
width:calc(100% - 236px);
}
input[type=submit]{
width:100%; height:30px; background:#007; color:#fff; border:0; border-radius:5px; margin-top:4px; cursor:pointer;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='content'>
<form id='form'>
<input type='text' id='num1' name='num1' /><div class='symbol'>&plus;</div><input type='text' id='num2' name='num2' /><div class='symbol'>&equals;</div><input type='text' class='er' id='total' name='total' value='Awaiting Input' readonly='readonly' />
<input type='submit' id='sub' value='Submit Test' />
</form>
</div>
</body>
</html>
Maybe something like this by simply extracting only numbers from any string the user inputs:
$(function () {
var $firstInput = $('#first');
var $secondInput = $('#second');
var $totalInput = $('#total')
$firstInput.keyup(updateTotal);
$secondInput.keyup(updateTotal);
function extractNumbers(str, def) {
var onlyNumbers = '';
for (var i = 0; i < str.length; ++i) {
var currChar = str.charAt(i);
if (!isNaN(currChar)) {
onlyNumbers += currChar;
}
}
return parseInt(onlyNumbers) || def;
}
function updateTotal () {
var valInput1 = extractNumbers($firstInput.val(), 0)
var valInput2 = extractNumbers($secondInput.val(), 0)
var total = valInput1 + valInput2;
$totalInput.val(total);
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<input type="text" placeholder="first number..." id="first">
<input type="text" placeholder="second number..." id="second">
<input type="text" placeholder="total number..." id="total">
</body>
</html>

Why counter is not increasing

please help me solve this code guys I am stuck here I am new to JavaScript that's why I can't solve this simple error
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
var scr1 = 0;
var scr2 = 0;
var counter = 0;
window.onload = function () {
var YS = document.getElementById("YS");
var CS = document.getElementById("CS");
var mid = document.getElementById("mid");
YS.innerHTML = "Your Score : " + scr1 + counter ;
CS.innerHTML = "Com Score : " + scr2 ;
}
function srt() {
counter++;
}
</script>
</head>
<body>
<h2 class="scr1" id="YS">Your Score :</h1>
<h2 class="scr2" id="CS">Com Score :</h2>
<br />
<br />
<center>
<div class="mid" id="mid"><p>0</p></p></div>
<div class="srt" id="none" onclick="srt()">
<h4>Start</h4>
</div>
</center>
</body>
</html>
I hope you understand my question please help me if you can
Thanks In Advance
Your counter is increasing, but you didn't show the change when it's increasing.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script>
var scr1 = 0;
var scr2 = 0;
var counter = 0;
window.onload = function () {
var YS = document.getElementById("YS");
var CS = document.getElementById("CS");
var mid = document.getElementById("mid");
}
function srt() {
console.log(counter);
counter++;
YS.innerHTML = "Your Score : " + scr1 + counter ;
CS.innerHTML = "Com Score : " + scr2 ;
}
</script>
</head>
<body>
<h2 class="scr1" id="YS">Your Score :</h1>
<h2 class="scr2" id="CS">Com Score :</h2>
<br />
<br />
<center>
<div class="mid" id="mid"><p>0</p></p></div>
<div class="srt" id="none" >
<button onclick="srt()">Start</button>
</div>
</center>
</body>
</html>
next time, use console.log() to do debugging
On Start div click you need to update your other Div to show the updated value.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
var scr1 = 0;
var scr2 = 0;
var counter = 0;
window.onload = function () {
var YS = document.getElementById("YS");
var CS = document.getElementById("CS");
var mid = document.getElementById("mid");
YS.innerHTML = "Your Score : " + scr1 + counter ;
CS.innerHTML = "Com Score : " + scr2 ;
}
function srt() {
counter++;
mid.innerHTML = counter;
YS.innerHTML = "Your Score : " + scr1 + counter ;
CS.innerHTML = "Com Score : " + scr2 ;
}
</script>
</head>
<body>
<h2 class="scr1" id="YS">Your Score :</h1>
<h2 class="scr2" id="CS">Com Score :</h2>
<br />
<br />
<center>
<div class="mid" id="mid"><p>0</p></p></div>
<div class="srt" id="none" onclick="srt()">
<h4>Start</h4>
</div>
</center>
</body>
</html>

jQuery set fontsize on change of value Strange behaviour

I am trying to change the font size of a paragraph using jQuery and Angular js.
Whenever user changes the font size the p tags font size will be changed,
it's working fine. But there's a small bug i.e whenever user sets the value the font size changes But if he decrease it , it doesn't decrease but increase, and vice versa and many these type of similar behaviour occur.
This is my code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>
p{
height: 600px;
width: 600px;
font-size:17px;
}
</style>
</head>
<body>
<div ng-app="myApp" ng-controller="editor">
<label for="kys_font_size"> font size:</label>
<select ng-model="kys_selected_font" id="fontsize" name="kys_font_size" ng-options="page for page in FontSize(1, 150)">
</select>
</div>
<p contenteditable="true" id="content" >
</p>
<p></p>
<script>
var app = angular.module('myApp',[]);
app.controller('editor',function($scope){
$scope.FontSize = function(start, end) {
var size = [];
for (var i = start; i <= end; i++) {
size.push(i);
}
return size;
};
$("#fontsize").on('change',function(){
$("#content").css("fontSize",$scope.kys_selected_font+"px");
});
});
</script>
</body>
</html>
Its working...
you have to use ng-change...
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>
p{
height: 600px;
width: 600px;
font-size:17px;
}
</style>
</head>
<body>
<div ng-app="myApp" ng-controller="editor">
<label for="kys_font_size"> font size:</label>
<select ng-model="kys_selected_font" id="fontsize" name="kys_font_size" ng-options="page for page in FontSize(1, 150)" ng-change="update()">
</select>
</div>
<p contenteditable="true" id="content" >
</p>
<p></p>
<script>
var app = angular.module('myApp',[]);
app.controller('editor',function($scope){
$scope.FontSize = function(start, end) {
var size = [];
for (var i = start; i <= end; i++) {
size.push(i);
}
return size;
};
$scope.update = function(){
$("#content").css("fontSize",$scope.kys_selected_font+"px");
}
});
</script>
</body>
</html>

Displaying one of two image (50 50 chance-coin toss) from a click button-javascript

I am trying to display one of two images using a click button using random number generator by assigning each image to an if and else statement. I'm not sure where the problem is. Here is what I have:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9</title>
<link href="images/avatar.png" rel="shortcut icon" type="image/png">
<link href="css/stylesheet.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" type="text/javascript"></script>
<style type="text/css">
.auto-style1 {
text-align: center;
}
</style>
<script type="text/javascript">
</script>
</head>
<body>
<header>
</header>
<aside>
</aside>
<div id="main">
<h1> Arrays and Coditional Statements</h1>
<h2 class="auto-style1">Flip a coin </h2>
<script>
function myFunction1() {
var result = doucment.getElementById("pic");
var x = Math.floor(Math.random() * 2);
console.log(x);
if (x == 0) {
document.getElementById("Coin").innerHTML = "Heads"
result.innerHTML="<img alt=\"the frontside of a coin\" src=\"images/heads.jpg\" />"; }
else {
document.getElementById("Coin").innerHTML = "Tails";
result.innerHTML= "<img alt=\"the backside of a coin\" src=\"images/tails.jpg\" />";
}
}
myFunction1();
</script>
<button type="button" onclick="myFunction1()" id="Coin">CLick ME</button>
<p id="pic"> </p>
</div>
<footer>
</footer>
</body>
</html>
You have a very simple typo. You wrote:
var result = doucment.getElementById("pic");
document is spelled wrong

Categories