JavaScript Calculating Value of Addition - javascript

I am unable to add 2 numbers taking from inputs.
<script>
x = document.getElementById('input1').value;
y = document.getElementById('input2').value;
z = Number(x)+ Number(y);
document.getElementById('submit1').addEventListener("click",alpha);
function alpha(){document.getElementById('div1').innerHTML="The answer is" + z;}
</script>
I need to do this with help of javaSCript only.

You could try something like this:
document.getElementById('submit1').addEventListener("click", function(){
// I suppose that the values you insert in your inputs are
// integers. Otherwise, you could use the parseFloat(value, 10)
// to parse float =s.
var x = parseInt(document.getElementById('input1').value);
var y = parseInt(document.getElementById('input2').value);
// Add the numbers
var z = x + y;
// Set the result in the selected div.
document.getElementById('div1').innerHTML="The answer is" + z;
});
You could try to run the following snippet:
document.getElementById('submit1').addEventListener("click", function(){
// I suppose that the values you insert in your inputs are
// integers. Otherwise, you could use the parseFloat(value, 10)
// to parse float =s.
var x = parseInt(document.getElementById('input1').value);
var y = parseInt(document.getElementById('input2').value);
// Add the numbers
var z = x + y;
// Set the result in the selected div.
document.getElementById('div1').innerHTML="The answer is " + z;
});
<input type="text" id="input1"/>
<br/>
<input type="text" id="input2"/>
<br/>
<div id="div1">
</div>
<br/>
<button id="submit1">submit</button>

You want to use parseInt() to turn a string into an int.
<html>
<head>
<title></title>
<style>
</style>
<script>
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("button").addEventListener("click",function(){
var a = parseInt(document.getElementById("input1").value);
var b = parseInt(document.getElementById("input2").value);
document.getElementById("output").innerHTML="The Answer is "+(a+b);
},false);
});
</script>
</head>
<body>
<input id="input1" type="text"/>
<input id="input2" type="text"/>
<button id="button">Add</button>
<div id="output"></div>
</body>
</html>

Related

How to fix the show/hide button on input change based on if/else condition

I am learning jquery. I have an HTML & jquery code. I want to show the button only if my answer is true on input value otherwise it should stay hidden. Also, I want to show the questions on my screen. See, if anyone can help. thanks
var random = Math.random();
var range = random * 2;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
var ans = 5;
$(document).ready(function() {
$("#bot").keyup(function() {
if (ans == floor) {
$("#pete").css("display", "block");
} else {
$("#pete").css("display", "none");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Name: <input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" style="display:none;">
use show() and hide() functions and i dont know when your floor and ans will be equal.
var random = Math.random();
var range = random * 2 ;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ans = 5;
floor=6; //for testing i gave
$("#bot").keyup(function() {
if (ans == $('#bot').val())
$("#pete").show();
else
$("#pete").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>What number comes after 4?</label>
<input type="number" id="bot" required="required"/>
<input type="submit" id="pete" style="display:none;" >
Here is the complete code for your requirement .
Use innerHTML to priint the question in the screen and .value to obtain the value entered by user ..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p id="question"></p>
<p>Name: <input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" style="display:none;" >
</body>
</html>
<script type="text/javascript">
var random = Math.random();
var range = random * 2 ;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
document.getElementById('question').innerHTML = ques1;
var ans = 5;
$("#bot").keyup(function() {
var ansFromInput = document.getElementById('bot').value;
console.log("ans , floor" , ans , ansFromInput);
if (ans == ansFromInput) {
$("#pete").css("display", "block");
}
else {
$("#pete").css("display", "none");
}
});
</script>
You can do something like that ,
Here using class to hide the button, we can add and remove class to achieve that.
var random = Math.random();
var range = random * 2;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
var floor = 5;
$('#ques').text(ques1);
$(document).ready(function() {
$('#bot').on('input',function(e){
if ($('#bot').val() == floor) {
$("#pete").removeClass('hide');
} else {
$("#pete").addClass('hide');
}
});
});
.hide{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> <p id="ques"> </p> </label>
<p><input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" class="hide">

How to accept the input from a text box and display in array format in jQuery?

I have written the code of taking input value from a text box and adding it to an array using the add button and also displaying the values of the array when the display button is clicked.
The thing is I did all this using JavaScript and now I want to do it using jQuery. I tried a code snippet from this website but it's not working. Please help.
<body>
<script src="jquery-3.3.1.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add" onclick="add_element_to_array();"></input>
<input type="button" id="button2" value="Display" onclick="display_array();"></input>
<div id="Result"></div>
<script>
var x = 0;
var sample = []; // <-- Define sample variable here
function add_element_to_array(){
$(document).on('click', '#btnSubmit', function () {
var test = $("input[name*='i_name']");
$(test).each(function (i, item) {
sample.push($(item).val());
});
console.log(sample.join(", "));
});
}
function display_array() {
var e = "<hr/>";
for (var y = 0; y < sample.length; y++) {
e += "Element " + y + " = " + sample[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
}
</script>
</body>
You can use this code to get idea of how it should work. You can also check for non-empty value before pushing the value into the array as an empty value in array will not make any sense.
$(document).ready(function(){
var valueArray = [];
//add value in array
$('#button1').click(function(){
var textValue = $('#text1').val();
//push non empty value only
if(textValue.trim() !== ''){
valueArray.push(textValue);
//reset the text value
$('#text1').val('');
}
});
//display value
$('#button2').click(function(){
$('#Result').html(valueArray.toString());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
I have added the jquery script considering the following as your suggested html.
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add"></input>
<input type="button" id="button2" value="Display"></input>
<div id="Result"></div>
The inptArr must be a global array.
<script>
var inptArr = [];
$('#button1').on('click',function(){
if($('#text1').val() != '')
inptArr.push($('#text1').val());
});
$('#button2').on('click',function(){
var string = '';
var lastIndex = parseInt(inptArr.length - 1);
for(var i = 0; i <= lastIndex ; i++)
{
if(i == lastIndex)
string += inptArr[i];
else
string += inptArr[i] + ',';
}
$('#Result').append(string);
});
</script>
This is another way to achieve what you want with minor changes.
You have only one text input element so don't need any each loop.
document.ready() is needed if you define script from starting of the code because at starting there is no defined element that have an id as btnSubmit so this block must wait to dom elements to be ready.
Also you don't need pure javascript code getElementById on display_array() function when you use jquery. You can change it as $("#Result").html(e);
var x = 0;
var array = [];
$(document).ready(function(){
$('#btnSubmit').on('click', function () {
array.push($("#text1").val());
});
});
function display_array() {
var e = "<hr/>";
for (var y = 0; y < array.length; y++) {
e += "Element " + y + " = " + array[y] + "<br/>";
}
$("#Result").html(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1"/>
<input type="button" id="btnSubmit" value="Add"/>
<input type="button" id="button2" value="Display" onclick="display_array();"/>
<div id="Result"></div>
In your code functions passed to onclick attributes are binding the click event to a DOM - don't do that.
var array = Array();
var input = $("#text1");
var result = $("#result");
function add_element_to_array(){
var value = input.val();
array.push(value);
console.log("Add:", value);
// input.val(""); // bonus: clears input after adding text to an array
}
function display_array() {
result.text(array.toString());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1">
<input type="button" id="button1" value="Add" onclick="add_element_to_array();">
<input type="button" id="button2" value="Display" onclick="display_array();">
<div id="result"></div>

how to use a global variable inside a function in javascript?

I want to use global variables 'x, y' in the below funcion.
it works when I put the variables inside the function
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
var x = document.getElementById('field_one').value
var y = document.getElementById('field_two').value
function calculator()
{
var p = x * y;
alert(x + " times " + y + " is " + p); //shows undefined times undefined is NaN
} // calculator()
</script>
</head>
<body>
<p>This is a simple calculator.</p>
<form name="the_form">
Number 1: <input type="text" value="" id="field_one"/> <br />
Number 2: <input type="text" value="" id="field_two"/> <br />
<input type="button" value="multiply them!" onclick="javascript:calculator()"/>
</form>
</body>
</html>
Your code works. But youre running in a race problem. You try to find Elements, before they are created:
var x, y;
window.onload = function() {
x = document.getElementById().value;
y = document.getElementById().value;
}
If your site is loading for a long time, the user may try to start the calculator script before x and y are set. Solution:
var x, y, calculator;
calculator = function() {
alert("please wait, until the site is completely loaded");
};
window.onload = function() {
x = document.getElementById().value;
y = document.getElementById().value;
calculator = function() {
alert(x + " times " + y + " is " + x * y);
};
}
The problem is as you want to get the value of x and y but them doesn't are setted value when function is called. If you want to use the variables many times, you need the create a function (I called setValues) that is responsible the set the value of x and y with the value of input, and always you need to get the values of input you can call it. Something like this:
var x;
var y;
function setValues() {
x = document.getElementById('field_one').value;
y = document.getElementById('field_two').value;
}
document.getElementById("calc").addEventListener("click", function() {
setValues();
var p = x * y;
alert(x + " times " + y + " is " + p);
}, false);
<p>This is a simple calculator.</p>
<form name="the_form">
Number 1: <input type="text" value="" id="field_one"/> <br />
Number 2: <input type="text" value="" id="field_two"/> <br />
<input type="button" id="calc" value="multiply them!" />
</form>
Positioning your script after the .html content guarantees everything is defined at the time you want the script working.
You can declare global variables from a local scope simply not using 'var' on declaration.
Do not forget to end each statement with a ';'
This way, your code is 100% functional:
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>This is a simple calculator.</p>
<form name="the_form">
Number 1: <input type="text" id="field_one"/> <br/>
Number 2: <input type="text" id="field_two"/> <br/>
<input type="button" value="multiply them!" onclick="readFields();"/>
<script type="text/javascript">
function readFields(){
x = document.getElementById('field_one').value;
y = document.getElementById('field_two').value;
calculator();
}
function calculator(){
var p = x * y;
alert(x + " times " + y + " is " + p); //shows undefined times undefined is NaN
} // calculator()
</script>
</form>
</body>
</html>

javascript: Could not add two text inputs

This does not add the numbers instead gives NaN
<html>
<body>
<script>
function checkit()
{
x = document.getElementById("a");
x1 = parseInt(x);
y = document.getElementById("b");
y1 = parseInt(y);
alert("Answer is" + (x1 + y1));
}
</script>
<input type="text" id="a">
<input type="text" id="b">
<input type="button" onclick="checkit()">
</body>
</html>
Even tried document.getElementById("a").value;
Still gives NaN
document.getElementById returns the HTML element (an input, in your case), not its value. Try this instead:
x = document.getElementById("a").value;

Why I Can't Get A Return Value To BAC?

<!DOCTYPE html>
<html>
<meta content="text/html; charset=utf-8">
<head>
<title>BAC Calculator</title>
//form for my html page. Not sure weather to use submit or just a button for this type. also if the return form is what is correct or not.
<form action="" onSubmit="return formbac()" id="formbac">
Weight:<input id="weight" name="weight1" type="number">
Beer:<input id="beer" name="beer1" type="number">
Wine:<input id="wine" name="wine1" type="number">
Shots:<input id="shots" name="shots1" type="number">
Time:<input id="time" name="time1" type="number">
<input name="submit" type="submit" value="Calculate">
<hr>
BAC: <input type="" name="bac" id="BAC">
</form>
</head>
<body>
//Javascript code for calculations
I think this is correct but i could possibly be mixing code up with my calculations//
<script>
// Basic function
function formbac(){
//values
var weight = document.getElementById("weight").value;
var beer = document.getElementById("beer" * .54).value;
var wine = document.getElementById("wine" * .6).value;
var shots = document.getElementById("shots" * .6).value;
var time= document.getElementById("time").value;
var BAC = 0;
//trying to get my output of baclevels
// calculations
var BAC = ((beer + wine + shots * 7.5) / (weight * .68)) - (0.015 * time);
//decimal round
var BAC = math.round(bac*100)/100;
//output
var BAC = document.getElementById(BAC).value;
}
</script>
</body>
</html>
Your output should be the other way around:
//output
document.getElementById('BAC').value = BAC;
Also, all the multiplications you're trying to perform inside document.getElementById should go outside. For example:
var beer = document.getElementById("beer").value * .54;
Try this line instead
document.getElementById("BAC").value = BAC; //notice "BAC" instead of BAC, you're trying to grab the element that doesn't exist
// calculations
var BAC = ((beer + wine + shots * 7.5) / (weight * .68)) - (0.015 * time);
//decimal round
var BAC = math.round(bac*100)/100; //override above value
//output
var BAC = document.getElementById(BAC).value; //override above value
As per your code your output will be the value of input control.

Categories

Resources