Suggestions with JavaScript operators - javascript

I am trying to make a application with JavaScript.
The app should have a plus, a minus button, and a clear button. In the middle there should be an input where a number will appear.
The app will start off with 1000 and plus will increase by 1000, the minus button will decrease it by 1000, and the clear button will reset the application. The minimum number in the app should be 1000.
I have figured out most but the plus button is not working as it should and I cannot get the app to have 1000 as minimum, it just continues into minus.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Application</title>
</head>
<style>
#application{
margin-top: 300px;
margin-left: 300px;
}
input[type=button]{
cursor: pointer;
padding: 10px 30px;
border-radius: 1px;
font-size: 2.5em;
}
input[type=text]{
padding: 10px 30px;
border-radius: 1px;
text-align: center;
font-size: 2.5em;
}
</style>
<body>
<section id="application">
<input id="substraction" type="button" value="-" onclick='substraction();'/>
<input id="number" value="1000" type="text">
<input id="addition" type="button" value="+" onclick='addition();'/>
<input type="button" value="Clear" onclick='clearText();'/>
</section>
<script>
function substraction(){
document.getElementById("tall").value -= 1000;
}
function addition(){
var numb = document.getElementById("number").value;
var add = 1000;
var total = number + add;
document.getElementById("tall").value = total;
}
function clearText(){
document.getElementById("number").value = "1000";
}
</script>
</body>

Just use a number <input> instead:
function clearText(){
document.getElementById("myNumber").value = 1000;
}
<input id="myNumber" type="number" step="1000" min="1000" max="1000000" value="1000">
<input type="button" value="Clear" onclick='clearText();'/>
This way, you can just use the step, min, and max attributes to specify the behavior of the input.

In Javascript + is also a string concatenation operator. If at least one of the operands is a String then the result is going to be a String also. You need to cast to Number type explicitly, because input value is always of a String type, even if it looks like a number "1000":
function addition() {
var number = Number(document.getElementById("number").value);
var add = 1000;
var total = number + add;
document.getElementById("tall").value = total;
}
Also instead of var numb you probably want var number.

In addition to the other answer, you're doing document.getElementById("tall").value = total; but no element with id "tall" exists. Perhaps it should be "number"?
In order to implement the minimum use the following code in subtract:
var number = Number(document.getElementById("number").value);
if(number - 1000 >= 1000)
document.getElementById("tall").value -= 1000;

Related

Create a JavaScript program that will compute for the Volume of a cuboid. Show the volume with complete description

The result does not appear. I'm quite new so I do not know what to do. I want the volume/result to appear. The code I used is:
<html>
<head>
<title>Calculate Area</title>
</head>
<body>
<h2 style = "color:blue;">Calculating Volume Rectangle</h2>
Length: <input type = "text" id = 'length'><br>
<br>
Width: <input type = "text" id = "width"><br>
<br>
<input type = "submit" value = 'Calculate Area' onclick = "calculate()">
<p>The Volume of the Rectangle is:</p>
<p id="answer" style='color:red;'></p>
</body>
<script>
function calculate()
{
var length = document.getElementById("length').value;
var width = document.getElementById("width").value;
var height = document.getElementById("width").value;
var result = (length) * (width) * (height)
document.getElementById("answer").innerHTML = (result);
}
</script>
</html>
Find the entire solution below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Calculate Area</title>
</head>
<body>
<h2 style="color: blue">Calculating Volume Rectangle</h2>
Length: <input type="text" id="length" /><br />
<br />
Width: <input type="text" id="width" /><br />
<br />
Height: <input type="text" id="height" /><br />
<button style="margin-top: 10px" onclick="calculate()">Calculate</button>
<div style="display: flex">
<p>The Volume of the Rectangle is:</p>
<p id="answer" style="color: red; margin-left: 10px"></p>
</div>
</body>
<script>
function calculate() {
var length = document.getElementById('length').value;
var width = document.getElementById('width').value;
var height = document.getElementById('height').value;
var result = length * width * height;
document.getElementById('answer').innerHTML = result;
}
</script>
</html>
you have some missing =, " and ' in the code and also parse string values to int for multiply.
<html>
<head>
<title>Calculate Area</title>
</head>
<body>
<h2 style="color:blue;">Calculating Volume Rectangle</h2>
Length: <input type="text" id="length"><br>
<br>
Width: <input type="text" id="width"><br>
<br>
Height: <input type="text" id="height"><br>
<br>
<input type="submit" value='Calculate Area' onclick="calculate()"> <!-- always use brakets when you are calling to a function -->
<p>The Volume of the Rectangle is:</p>
<p id="answer"></p>
</body>
<script>
function calculate() {
var length = document.getElementById("length").value;
var width = document.getElementById("width").value;
var height = document.getElementById("height").value;
var result = parseInt(length) * parseInt(width) * parseInt(height); //convert extracted string values to integers
document.getElementById("answer").innerHTML = result;
}
</script>
</html>
I did some corrections, you can check it out on this link:
https://codesandbox.io/embed/strange-colden-w92gbw?fontsize=14&hidenavigation=1&theme=dark
But basically:
On line 15, you put an onClick but pass the value link a string calculate, pass an empty param calculate() in the onClick and in the function on line 21.
On line 22 at the end of var length theres a ("length').value, I changed to ("length").value;
I hope it can help you.
<h2 style = "color:blue;">Calculating Volume Rectangle</h2>
Length: <input type = "text" id ='length'><br>
<br>
Width: <input type="text" id="width"><br>
<br>
<input type="submit" value = 'Calculate Area' onclick = "calculate()">
<p>The Volume of the Rectangle is:</p>
<p id ="answer" style='color:red;'></p>
</body>
<script>
function calculate(){
var length = document.getElementById("length").value;
var width = document.getElementById("width").value;
var height = document.getElementById("width").value;
var result = (length) * (width) * (height)
document.getElementById("answer").innerHTML = (result);
}
</script>
Here is a list of the most relevant points concerning the many problems that plagues the OP code:
If you are using more than one form control (ex. <input>, <button>, <output>, etc), wrap everything in a <form>. Having a <form> allows you to use very useful interfaces:
HTMLFormElement
HTMLFormControlsCollection
Keep in mind, all HTML is basically strings. An htmlString is a string that can be parsed into HTML, all values of HTML attributes are strings, the only time when value of form controls are accessible real numbers is when it is extracted as a string then converted into a real number. There are a few ways to convert a string into a number:
.parseInt() method
.parseFloat() method
Number() constructor
* / - + operators by cohersion (+is used through out the example)
Finally, event delegation is used to handle the "input" Events on each <input> within the <form>. Also, do not use inline event attributes -- inline event handlers are garbage.
// Reference <form>
const calc = document.forms.calc;
// Register the "input" event to <form>
calc.oninput = calcDim;
// Event handler passes Event Object
function calcDim(e) {
/*
HTMLFormControlsCollection (all <input>, <button>, <output>, <fieldset>)
e.target references the element the user is currently typing into.
*/
const io = this.elements;
const active = e.target;
/*
If >active< [name="num"]...
...if >H< is [disabled] OR it's .value = 0...
...>result< .value = >L< * >W<...
...Otherwise >result< .value = >L< * >W< * >H<
*/
if (active.name === 'num') {
if (io.H.disabled === true || +io.H.value === 0) {
io.result.value = +io.L.value * +io.W.value;
} else {
io.result.value = +io.L.value * +io.W.value * +io.H.value;
}
}
/*
If >L< .value AND >W< .value are both greater than 0...
...>H< is not [disabled]...
...Otherwise >H< is [disabled]
*/
if (+io.L.value > 0 && +io.W.value > 0) {
io.H.disabled = false;
} else {
io.H.disabled = true;
}
/*
If >H< .value is greater than 0...
...The result <label> [data-dim] is 'Volume'...
...Otherwise it's 'Area'
*/
if (+io.H.value > 0) {
document.querySelector(`[for='result']`).dataset.dim = 'Volume';
} else {
document.querySelector(`[for='result']`).dataset.dim = 'Area';
}
};
*, *::before, *::after {box-sizing: border-box;}
html {font: 2.5ch/1.15 'Segoe UI'}
h1 {font-size: 1.6em; margin-bottom: 4px;}
h2 {font-size: 1.4em;}
fieldset {width: 30ch; padding-left: 25px;}
legend {margin: 0 0 1ch -1ch; font-size: 1.25rem;}
input, output {display: inline-block; width: 10ch; font: 2ch/1.15 Consolas; text-align: center}
label {display: inline-block; width: 8ch;}
[for='result']::before {content: attr(data-dim)}
[for='result']::after {content:': '}
#L {width: 10.05ch; margin-left: -1px;}
#result {margin-left: -8px;}
[disabled='true'] {opacity: 0.4;}
<!DOCTYPE html>
<html lang='en'>
<head>
<title></title>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>
<style>
/* CSS Block */
</style>
</head>
<body>
<header>
<h1>Area/Volume</h1>
<h2>Calculator</h2>
</header>
<main>
<form id='calc'>
<fieldset>
<legend>Length, Width, & Hieght</legend>
<label for='L'>Length: </label>
<input id='L' name='num' type='number' min='0' placeholder='0'><br>
<label for='W'>Width: </label>
<input id='W' name='num' type='number' min='0' placeholder='0'><br>
<label for='H'>Hieght: </label>
<input id='H' name='num' type='number' min='0' placeholder='0' disabled><br>
</fieldset>
<fieldset>
<label for='result' data-dim='Area'></label>
<output id='result'></output>
</fieldset>
</form>
</main>
<script>
/* Inline JavaScript */
</script>
</body>
</html>

How to format a calculated number result with thousand comma separator

I'm very new to javascript and created a simple calculator that calculates cost based on quantity with +/- buttons controlling the quantity input. It works how I want it to, but I can't figure out how to format the cost result with thousand comma separators once the cost estimate exceeds $1000 with 2 items.
In other words, when you increase quantity to 2, how do you get it to print as $1,400 instead of $1400?
Here's what I tried below
$(document).ready(function() {
$(".calculator").on("input", ".quantity", function() {
var price = +$(".price").data("price");
var quantity = +$(this).val();
$("#total").text("$" + price * quantity);
})
var $buttonPlus = $('.increase-btn');
var $buttonMin = $('.decrease-btn');
var $quantity = $('.quantity');
/*For plus and minus buttons*/
$buttonPlus.click(function() {
$quantity.val(parseInt($quantity.val()) + 1).trigger('input');
});
$buttonMin.click(function() {
$quantity.val(Math.max(parseInt($quantity.val()) - 1, 0)).trigger('input');
});
})
/*For number formatting*/
$(document).on('input', '.total', function() {
var x = $(this).val();
$(this).val(x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
});
.checkout {
height: 300px;
width: 400px;
margin: 20px auto;
}
input {
text-align: center;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="calculator">
<h1 class="title">Estimate Cost</h1>
<p class="price" data-price="700">$700 per item</p>
<p class="description">Quantity:</p>
<button type="button" class="decrease-btn">-</button>
<input type="text" class="quantity" value="1">
<button type="button" class="increase-btn">+</button>
<p class="total">Total: <span id="total">$700</span></p>
</div>
Okay you have some problems in the code. You are trying to treat a p as an input element. You are close to getting it, you just need to do the formatting where you set the text.
$(document).ready(function() {
$(".calculator").on("input", ".quantity", function() {
var price = +$(".price").data("price");
var quantity = +$(this).val();
const total = '$' + (price * quantity).toFixed(2).replace(/,\$/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
$("#total").text(total);
})
var $buttonPlus = $('.increase-btn');
var $buttonMin = $('.decrease-btn');
var $quantity = $('.quantity');
/*For plus and minus buttons*/
$buttonPlus.click(function() {
$quantity.val(parseInt($quantity.val()) + 1).trigger('input');
});
$buttonMin.click(function() {
$quantity.val(Math.max(parseInt($quantity.val()) - 1, 0)).trigger('input');
});
})
.checkout {
height: 300px;
width: 400px;
margin: 20px auto;
}
input {
text-align: center;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="calculator">
<h1 class="title">Estimate Cost</h1>
<p class="price" data-price="700">$700 per item</p>
<p class="description">Quantity:</p>
<button type="button" class="decrease-btn">-</button>
<input type="text" class="quantity" value="1">
<button type="button" class="increase-btn">+</button>
<p class="total">Total: <span id="total">$700</span></p>
</div>

JavaScript: Number Sequence with a For Loop

JS:
function myarray (){
}
var starting=document.getElementById("starting");
var ending=document.getElementById("ending");
var step=document.getElementById("step");
var results=document.getElementById("myarray")
if (i>=0){
var result=starting
}
for (var starting>=0; myarray<=ending; i+=step)
document.writeln(myarray[i+=step]){
}
HTML:
<div id="results">Here are the even numbers between "startingnumber" and "endingnumber" by "step"&nnsp's
<!DOCTYPE html>
<html>
<head>
<title>A Web Page</title>
</head>
<script src="Guild_Practice.js"></script>
<style media="screen">
table {
width:40%;
}
.titles {
text-align: right;
color: green;
font-family: arial;
font-weight: bold;
padding-bottom: 10px;
}
caption {
font-size: 32px;
font-weight: bold;
font-family: cursive;
color: red;
}
.displayevens {
text-align: center;
padding-top: 10px;
}
}
</style>
<body>
<table>
<caption>Sample</caption>
<form>
<tr>
<!--Starting Number Line with Form -->
<td class="titles">Starting Number</td>
<td class="align-left"><input type="text" id="starting"></td>
</tr>
<tr>
<!-- Ending Number Line with Form -->
<td class="titles">Ending Number</td>
<td class="align-left"><input type="text" id="ending"></td>
</tr>
<tr>
<!-- Step Line with Form -->
<td class="titles">Step</td>
<td class="align-left"><input type="text" id="step"></td>
</tr>
<tr>
<!-- Button covered in both columns -->
<td class="displayevens" colspan="2"><button type="button">Display Evens</button></td>
</tr>
</form>
</table>
</body>
</html>
I have to allow a user to enter a starting number an ending number and a step value into three textboxes on a page (which I have created). A button will be present that when clicked should output all the even numbers between the start and end value.
My questions are:
How does my js code look so far?
How do I make a phrase such as: "Here are the even numbers between 4 and 20 by 3's" and then list out the numbers. It will appear once I click the button.
You could take the values and cast it to number with an unary plus and iterate from starting to ending with the given step. With each loop check if the actual counter is even and add it to the result set.
Later display the result in results.
function myarray() {
var starting = +document.getElementById("starting").value,
ending = +document.getElementById("ending").value,
step = +document.getElementById("step").value,
results = document.getElementById("results"),
i,
array = [];
for (i = starting; i <= ending; i += step) {
i % 2 || array.push(i);
}
results.innerHTML = array.join(', ');
}
<pre><form>Starting Number: <input type="text" id="starting"><br>Ending Number: <input type="text" id="ending"><br>Step: <input type="text" id="step"><br><button type="button" onclick="myarray()">Display Evens</button></form><div id="results"></div></pre>
So it isn't so much that you want the even numbers, you simply want the incremental steps between your starting and ending point. Is that correct? And I assume this is a school assignment? Try something like this to kick you off. I've created the HTML elements, and I've retrieved the values of the inputs. Now you get to create the logic for the increment (try a FOR loop) and insert the results into the progression-pane.
/*****
* When the "show me!" button gets clicked,
* there's a few things we do: get the values of
* the inputs, loop from the starting value to
* the ending value by a given increment (default
* increment of two), and output the result to a div.
*****/
runCounter = function() {
// This is the location we'll put the result
var contentPane = document.getElementById("progression-pane");
// This will be the output string
var contentString = "";
// retrieve the values given AND MAKE THEM
// INTEGERS! We could do floats, but it's
// darn important to make them numbers.
var startingValue = parseInt(document.getElementById("startingValue").value);
var endingValue = parseInt(document.getElementById("endingValue").value);
var increment = parseInt(document.getElementById("incrValue").value);
if (startingValue && endingValue) {
// So long as we actually HAVE a staring and ending value...
if (!increment) increment = 2;
// If we don't have an increment given, let's count by twos!
contentString += "<p>The values between " + startingValue + " and " + endingValue + " in increments of " + increment + ":</p><ul>";
for (i = startingValue; i <= endingValue; i += increment) {
// If we are here, we have all three: start, end and increment
contentString += "<li>" + i + "</li>";
}
contentString += "</ul>";
// We've finished formatting the string,
// let's output it to the proper div.
// Note that I'm using innerHTML,
// document.writeln is considered bad.
contentPane.innerHTML = contentString;
}
}
label {
display: block;
font-weight: bold;
}
<label for="startingValue">Start:</label>
<input type="text" id="startingValue" />
<label for="endingValue">End:</label>
<input type="text" id="endingValue" />
<label for="startingValue">Increment:</label>
<input type="text" id="incrValue" />
<button onclick="runCounter()">Show me!</button>
<div class="content-pane">
<h2>Your progression:</h2>
<div id="progression-pane">
</div>
</div>
The bulk of the above javascript is actually comments discussing what I'm doing. Get in that habit, so you don't lose track of variables! And yours works fine, but innerHTML is considered better form than document.writeln
Ok, so if in fact you want the EVEN numbers at the given step intervals, change the line that actually appends the line items like this:
// Now, we want to see if this is an even number
if(i%2 == 0)
contentString += "<li>" + i + "</li>";
See this version running as a fiddle here

Can somebody explains that why my input fields value is not changing

I am making a simple word counter program in JavaScript. I am fairly new in JavaScript world so excuse me if I am asking an rudimentary and simple enough question. I'm getting everything working that the string of text from textarea is splitted into words array and i can log number of words to console but can't display them into a text field where I want them to appear. Hope that someone can help here. Thanks
var btn = document.getElementById("btn");
var numWords = document.getElementById("output");
var str = document.getElementById("txtBox");
btn.onclick = function()
{
var words = str.value.split(" ");
numWords.innerHTML.value = words.length;
console.log( words.length );
};
.container
{
width: 600px;
margin: 0 auto;
}
textarea
{
width: 560px;
padding: 10px;
background-color: #dfdfdf;
color: #333;
font-size: 18px;
}
input
{
text-align: center;
padding: 10px;
margin-top: 15px;
}
input[type="submit"]
{
float: right;
margin-right: 15px;
background-color: #84ac49;
border: 0;
color: #fff;
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="container">
<from>
<textarea name="txtBox" id="txtBox" cols="30" rows="10"></textarea><br/>
<input type="text" value = 0 id="output">
<input type="submit" value="Count Words" id="btn">
</from>
</div>
</body>
</html>
move getting value in click function event
btn.onclick = function()
{
var str = document.getElementById("txtBox").value
var words = str.split(" ");
numWords.value = words.length;
console.log( words.length );
};
JSFIDDLE
btn.onclick = function () {
var words = str.value.split(" ");
numWords.value = words.length;
console.log(words.length);
};
also you can set input like this:
<input value="Count Words" id="btn">
when You click on count button You will get word count.
HTML
<textarea id="inputString" cols="50" rows="4"></textarea>
<br>
<input type="button" name="Convert" value="Count Words" onClick="countWords();">
<input id="wordcount" type="text" value="0" size="6">
Javascript
countWords=function(){
s=document.getElementById("inputString").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
document.getElementById("wordcount").value = s.split(' ').length;
}
Here is a demo :https://jsfiddle.net/DhwaniSanghvi/tdn3x72g/

Multiple plus and minus buttons

I am using - and + buttons to change the number of the text box, I am having troubles dealing with different text fields, here is my code:
var unit = 0;
var total;
// if user changes value in field
$('.field').change(function() {
unit = this.value;
});
$('.add').click(function() {
unit++;
var $input = $(this).prevUntil('.sub');
$input.val(unit);
unit = unit;
});
$('.sub').click(function() {
if (unit > 0) {
unit--;
var $input = $(this).nextUntil('.add');
$input.val(unit);
}
});
button {
margin: 4px;
cursor: pointer;
}
input {
text-align: center;
width: 40px;
margin: 4px;
color: salmon;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id=field1>
field 1
<button type="button" id="sub" class=sub>-</button>
<input type="text" id="1" value=0 class=field>
<button type="button" id="add" class=add>+</button>
</div>
<div id=field2>
field 2
<button type="button" id="sub2" class=sub>-</button>
<input type="text" id="2" value=0 class=field>
<button type="button" id="add2" class=add>+</button>
</div>
And here's the DEMO
You can see in the demo that the values change correctly only if you click buttons on the same field, but if you alternate between fields the values don't change properly.
This should be all you need:
$('.add').click(function () {
$(this).prev().val(+$(this).prev().val() + 1);
});
$('.sub').click(function () {
if ($(this).next().val() > 0) $(this).next().val(+$(this).next().val() - 1);
});
By using the unit variable you were tying both inputs together. And the plus in +$(this) is a shorthand way to take the string value from the input and convert it to a number.
jsFiddle example
You're using the same variable to hold the values of your two inputs. One simple option would be to use two variables instead of one:
var unit_1 = 0;
$('#add1').click(function() {
unit_1++;
var $input = $(this).prev();
$input.val(unit_1);
});
/* Same idea for sub1 */
var unit_2 = 0;
$('#add2').click(function() {
unit_2++;
var $input = $(this).prev();
$input.val(unit_2);
});
/* Same idea for sub2 */
and unit = unit just assigns the value of unit to itself, so that's no very useful and you can certainly leave it out.
An alternative approach is to use data attributes and have each element store its own value. Edit: it already stores its own value. Just access it.
var total;
// if user changes value in field
$('.field').change(function() {
// maybe update the total here?
}).trigger('change');
$('.add').click(function() {
var target = $('.field', this.parentNode)[0];
target.value = +target.value + 1;
});
$('.sub').click(function() {
var target = $('.field', this.parentNode)[0];
if (target.value > 0) {
target.value = +target.value - 1;
}
});
button {
margin: 4px;
cursor: pointer;
}
input {
text-align: center;
width: 40px;
margin: 4px;
color: salmon;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id=field1>
field 1
<button type="button" id="sub" class=sub>-</button>
<input type="text" id="1" value=0 class=field>
<button type="button" id="add" class=add>+</button>
</div>
<div id=field2>
field 2
<button type="button" id="sub2" class=sub>-</button>
<input type="text" id="2" value=0 class=field>
<button type="button" id="add2" class=add>+</button>
</div>

Categories