Basic math functions in JavaScript to show on HTML page - javascript

I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>

Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">

First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)

Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!

There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}

To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}

Related

Javascript Arrays. Adding, subtracting and totaling

I'm having a little trouble with an assignment a teacher dished out to my class involving javascript arrays. What they essentially want us to do is to create sort of cart / calculator hybrid that allows users to input numbers, store them and array and display those numbers on the webpage, then be able to either add them together for a total or reset them and start over.
I think I more or less know how to make a reset button, and I believe I've figured out how to add items to the array efficiently enough, but I'm kinda stumped on how to show those items on an html page and how to add them together to make and show a total. Any help would be appreciated, I'm kinda new at this and so far the instructions from our source material are a bit vague and hard to understand, at least for me!
So far I have some simple html for the input field and an "add number" button which will add the input field to the array (I will limit it to numbers only later and will).
<form onsubmit="return userNumber()">
<p>Number:</p>
<input type="text" id="box" />
<br>
<input type="button" value="Add Number" />
<input type="button" value="Calculate" />
<input type="button" value="Reset" />
</form>
I've no code yet for the Calculate or Reset button, but for the Add Number button which does seem to work properly when I bring up the console, I just need it to also display on the webpage. Here's what I have for that.
var numbers = [];
function userNumber() {
boxvalue = document.getElementById('box').value;
numbers.push(boxvalue);
console.log(numbers);
return false;
}
I've attached an image of what our teacher showed us, they want us to make it only similar in function, looks are not as important.
Once again, thank you to anyone who can assist, I'm very lost on where to go from here!
First, give them all an id. It's a lot easier to work with them when they all have the "names". And then you can easily handle the events (clicks in this example).
Notice, when you click on the "Add" button, before push you need to use parseInt(string, base) since input.value is a string, and + operator is concatenation for string, not addition. Like sum += numbers[i]; below.
And there is a couple of protection for corner cases when you click the "Calculate" button with an empty numbers array for example.
var numbers = [];
var boxInput = document.getElementById("box");
var addBtn = document.getElementById("add");
var calculateBtn = document.getElementById("calculate");
var resetBtn = document.getElementById("reset");
var allNumbers = document.getElementById("all-numbers");
var calculatedNumbers = document.getElementById("calculated-numbers");
addBtn.addEventListener("click", function() {
if (boxInput.value.length > 0) {
numbers.push(parseInt(boxInput.value, 10));
boxInput.value = "";
}
allNumbers.innerHTML = numbers.join(" ");
});
calculateBtn.addEventListener("click", function() {
if (numbers.length === 0) {
return;
}
for (var i = 0, sum = 0; i < numbers.length; i++) {
sum += numbers[i];
}
calculatedNumbers.innerHTML = numbers.join(" + ") + " = " + sum;
});
resetBtn.addEventListener("click", function() {
numbers = [];
boxInput.value = "";
allNumbers.innerHTML = "";
calculatedNumbers.innerHTML = "";
});
<p>
<label for="box">Number:</label>
<input id="box" type="number" />
</p>
<p>
<input type="button" id="add" value="Add Number" />
<input type="button" id="calculate" value="Calculate" />
<input type="button" id="reset" value="Reset" />
</p>
<h3>Numbers added:</h3>
<p id="all-numbers"></p>
<h3>Sums of numbers added:</h3>
<p id="calculated-numbers"></p>

radio button .checked to perform a math expression using user input javascript

I have two textboxes where a user enters a number into each one and then clicks a radio button to select the mathematical operation to be performed upon the calculate button.This is for a homework assignment, so only javascript and html
are being used, no jquery. Currently when I click the button, nothing appears to happen and I am getting no console errors...
HTML
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1">
2nd number: <input type="text" name="number2">
<br>
<input type="radio" name="add">Add <br>
<input type="radio" name="subtract">Subtract <br>
<input type="radio" name="multiply">Multiply <br>
<input type="radio" name="division">Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
Javascript
function calculate(){
var num1 = parseInt("document.getElementsByName('number1').value;", 10);
var num2 = parseInt("document.getElementsByName('number2').value;", 10);
var add = document.getElementsByName("add");
var sub = document.getElementsByName("subtract");
var multi = document.getElementsByName("multiply");
var divis = document.getElementsByName("division");
var res = document.getElementById("math_res").innerHTML;
if (add.checked == true){
res = num1 + num2;
}
else if ( sub.checked == true){
res = num1 + num2;
}
else if (multi.checked == true){
res = num1 * num2;
}
else if (divis.checked == true){
res = num1 / num2;
}
}
I thought my function would take the input from the two text boxes and convert the user input to an integer and assign them to variable num1 and num2. Then assign each radio button to a variable to reduce typing of document.get...
that each if statement would check to see if that radio but was checked. If true perform calculation if false move to next if statement and display the results in a paragraph element.
where did I go wrong?
You have a couple of issues.
getElementsByName returns a collection of elements, not a single element so:
var add = document.getElementsByName("add");
will assign undefined to add. But you don't need to use it, just reference the controls as named properties of the form. Pass a reference to the button from the listener:
<input type="button" name="calc" onclick="calculate(this)" value="Calculate">
Then in the function get the form:
function calculate(element) {
var form = element.form;
Now just do:
var num1 = parseInt(form.number1.value, 10);
and so on, which also fixes the other issues you have with referencing the controls.
Also, radio buttons need to have the same name so that only one is selectable, so as Felix says, give them all the same name and differentiate on value (or class or some other attribute value). You'll need to loop over them to find out the operation to perform, so the HTML might be:
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
Then to get the operation:
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
Now check the value of op to work out whether to add, subtract, etc.
Here's a quick example, I don't recommend inline scripts like this but it's handy for playing.
<form>
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
<input type="button" onclick="
var form = this.form;
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
form.selectedOperation.value = op || 'No operation selected';
" value="Get selected operation">
<input type="text" readonly name="selectedOperation"><br>
<input type="reset">
</form>
There are a few issues I can notice.
1.
getElementsByName returns a NodeList, which is Array-like. You need to retrieve the first element in the NodeList before accessing its value. For example,
document.getElementsByName('number1')[0].value
2.
You are passing a literal code string to parseInt. You should write something like
parseInt(document.getElementsByName('number1')[0].value, 10);
3.
The code var res = document.getElementById('math_res').innerHTML stores a reference to the innerHTML of the element. When you assign res = num1 + num2 for example, you are simply overwriting the reference, instead of actually altering the innerHTML. To correct this,
var elem = document.getElementById('math_res');
// later...
elem.innerHTML = num1 + num2;
4. You are incorrectly defining multiple radio buttons with different names. In order for the browser to render them as a "radio button group" where only one can be selected, they must have the same name, but different "value" attributes. See RobG's answer or the Plunkr below for an example of how to define the radio button group and extract its value using JavaScript.
A working version of your code is here.
Edit Please note that these are minimal edits to make your code work. RobG's answer shows a more correct way of extracting the values of form fields.
Here is my version, hope it helps you.
<!DOCTYPE html>
<html>
<body>
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1" id = 'number1'>
2nd number: <input type="text" name="number2" id = 'number2'>
<br>
<input type="radio" name="button" id = 'add' >Add <br>
<input type="radio" name="button" id = 'substract'>Subtract <br>
<input type="radio" name="button" id = 'multiply'>Multiply <br>
<input type="radio" name="button" id = 'division'>Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
<script>
function calculate(){
//Obtaining the references to the text inputs
var number1 = parseInt(document.getElementById('number1').value);
var number2 = parseInt(document.getElementById('number2').value);
//Reference of the result Box
var resultBox = document.getElementById('math_res');
resultBox.innerHTML = '';
//Reference of the radio buttons
var buttonAdd = document.getElementById('add');
var buttonSubstract = document.getElementById('substract');
var buttonMultiply = document.getElementById('multiply');
var buttonDivision = document.getElementById('division');
//Make the magic
if(buttonAdd.checked == true){
resultBox.innerHTML = number1 + number2
}
else{
if(buttonSubstract.checked == true){
resultBox.innerHTML = number1 - number2
}
else{
if(buttonMultiply.checked == true){
resultBox.innerHTML = number1 * number2
}
else{
if(buttonDivision.checked == true){
resultBox.innerHTML = number1 / number2
}
}
}
}
}
</script>
</body>

Limiting Text Input Based On Another Text Input

It seems pretty simple but I can't find a good way to do it.
I am doing a research bar which allow users to search something in terms of price mini and price maxi.
So :
I have two text input types (in html of course) "price_mini?" and "price_maxi?".
"Price_mini" cannot be bigger than "price_maxi".
How can I limit the users input of "price_mini" so that if does not allow the user to enter more than the "price_maxi" variable's input and then display an error on save(search) if the mini number is bigger than price_maxi.
Something like this should work, I couldn't get JSFiddle to handle the form to show you a good example and I don't do much in plain javascript now in days so pardon me if there is a small error or two.
HTML
<form name="myForm" onSubmit="submit()" method="post">
<input name="price_mini" type="text">
<input name="price_maxi" type="text">
<input type="submit" value="Submit">
</form>
Javascript
function submit(){
var price_mini = document.forms["myForm"]["price_mini"].value;
var price_maxi = document.forms["myForm"]["price_maxi"].value;
if(Number(price_mini) > Number(price_maxi)){
alert("Minimum price must be less than maximum price!");
}else{
// Your search code here
}
}
Imagine this html
<input id="min" type="text">
<input id="max" type="text">
This should be the correct javascript
var min = document.getElementById("min");
var max = document.getElementById("max");
min.change(function() {
if(Number(this.value) > Number(max.value)) {
this.value = max.value; // replace min with the same max value if it's bigger
}
}
Let's assume that this is your HTML.
<input id="min" type="text">
<input id="max" type="text">
The working JavaScript is this with the behavior if the max field is empty.
var min = document.querySelector('#min');
var max = document.querySelector('#max');
var calculate = function() {
if(max.value == '') return;
if(Number(min.value) > Number(max.value)) {
min.value = max.value;
}
}
min.addEventListener('input', calculate);
max.addEventListener('input', calculate);
You should compare them when they have value (min && max). If you notice that min is higher you can alert to the user or change it automatically to the lowest or to the highest.
$('.calc_input').change( function() {
var min = $('#min').val();
var max = $('#max').val();
if ( (min && max) && min > max ) {
alert('This can not be!');
// $('#min').val() = max;
// $('#max').val() = min;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Min:<input id="min" class="calc_input">
<br>
Max:<input id="max" class="calc_input">

Javascript: Cant fetch value of input number box

Hello almighty internetz!
Im totally new on javascript, and i cant get the script to fetch numbers from input boxes, plus the sums together and write it out.
Have been sitting on Google for an hour now, so im asking you guys/girls for help!
http://jsfiddle.net/heWM2/5/
<form action="" id="brod">
<p>Pris per kartong
<input name="Prisperkartong" type="number" id="priskart" name="pris">
</p>
<p>Antal kartonger i leverans
<input name="Kartongilev" type="number" id="kartilev">
</p>
<input type="button" onClick="calculateTotal()" value="Räkna">
<div id="print"></div>
</form>
And the Javascript:
function getPrisperkartong() {
var Prisperkartong = parseInt(document.brod.priskart.value, 10);
if (isNaN(Prisperkartong)) return;
document.bord.priskart.value = Prisperkartong;
}
function getKartongilev() {
var Kartongilev = parseInt(document.brod.kartilev.value, 10);
if (isNaN(Kartongilev)) return;
document.bord.kartilev.value = Kartongilev;
}
function calculateTotal() {
var total = getPrisperkartong() + getKartongilev();
var divobj = document.getElementById('print');
divobj.style.display = 'block';
divobj.innerHTML = "Pris $" + total;
}
If you are accessing the input boxes through the form, you need to use the name field to identify the form as well as the input boxes. Your get functions should also return the value, not assign it back to the original input box. See this updated fiddle for a fixed, working example.
http://jsfiddle.net/heWM2/6/

How to get auto + javascript input fields

I'm trying to get an autosum from fields, the issue is that if the total of fields are without value the script is not working correctly, and also if there are more than 7 fields again the script is not working.
here is the javascript:
function getTotal()
{
var value01 = document.getElementById('value01').value;
var value02 = document.getElementById('value02').value;
var value03 = document.getElementById('value03').value;
var value04 = document.getElementById('value04').value;
var value05 = document.getElementById('value05').value;
var value06 = document.getElementById('value06').value;
var value07 = document.getElementById('value07').value;
// Add them together and display
var sum = parseInt(value01) + parseInt(value02) + parseInt(value03) + parseInt(value04) + parseInt(value05) + parseInt(value06) + parseInt(value07);
document.getElementById('sum_total').value = sum;
}
inputs:
<input type="text" id="value01" />
<input type="text" id="value02" />
<input type="text" id="value03" />
here is starting to be added with a button more input fields.
<input type="text" id="+" />
<input type="text" id="++" />
<input type="button" value="Add Them Together" onclick="getTotal();" />
my question is, how can i get an auto + on var value01 02 03 etc.
Any help is appreciated.
Your question is not very clear and so I'm not too sure what you are wanting to do so feel free to offer clarification for optimum assistance. On that note, based off of what you have provided, I have two things to point out:
1) Your ID of "+" is not valid. Per the HTML 4 spec:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").
2) Instead of creating a different var containing each value, I would recommend creating a function that you can use within a for loop that will determine the sums of each incremental input. This is more DRY and helps simplify things if the number of inputs were to grow.
function getValues(id){
return document.getElementById(id).value;
}
The pure JavaScript solution below begins with one input box and will add additional inputs with the click of a button, which I believe is what you're looking for. You can modify the number of initial input boxes accordingly, but it should give you an idea.
Javascript:
var max = 1;
function getValues(id){
var result = document.getElementById(id).value;
return (result ? result : 0);
}
function addInput(){
max++;
var input = '<input type="text" id="value'+ max +'" />';
document.getElementById("valuesContainer").innerHTML += input;
}
function getTotal(){
var sum = 0;
for(var i=1; i <= max; i++){
sum = sum + parseFloat(getValues("value" + i));
}
document.getElementById("total").innerHTML = sum;
}
HTML:
<div id="valuesContainer">
<input type="text" id="value1" />
</div>
<input type="button" value="Add Value" id="addMore" onclick="addInput();" />
<input type="button" value="Calculate Total" onclick="getTotal();" />
<div id="total"></div>
Demo: http://jsfiddle.net/Y4xgU/

Categories

Resources