Javascript eval() input field and output answer in same field - javascript

I am learning and want to know if there is a way to do this, let's say I have HTML input field:
<input type=text id="input">
Nearby I would have one button:
<button id="equal">=</button>
I want to write javaScript that would evaluate statement (if it is an equation like "2+3" "6/2" etc) in that text field and replace that statement with an answer for the equation. What I tried:
var equal = document.querySelector("#equal");
var input = document.querySelector("#input");
equal.addEventListener('click', function () {
eval(input.value) += input.innerText;
});
I already made only possible input 1234567890 and /*-+
If there is a way, I would highly appreciate the answer with explanation, started javaScript just recently so it is still like a dark forest for me, but I do have a wish to have a better understanding of it. :)

You just need to swap eval(input.value) += input.innerText to input.value = eval(input.value)
var equal = document.querySelector("#equal");
var input = document.querySelector("#input");
equal.addEventListener('click', function() {
input.value = eval(input.value);
});
<input type=text id="input">
<button id="equal">=</button>
Also, it would be recommended to use document.getElementById instead of document.querySelector, though there isn't much difference (mainly compatibility with older browsers). Read more

You want the place where you type in the expression to be different than the place where you display it:
<!DOCTYPE html>
<html>
<body>
<button id="evaluate">Get answer</button>
<input id="input" />
<p id="result">waiting for answer...</p>
<script>
var evaluate = document.getElementById("evaluate");
var input = document.getElementById("input");
var result = document.getElementById("result");
evaluate.addEventListener('click', function () {
try {
result.textContent = eval(input.value);
}
catch (error) {
result.textContent = "waiting for answer...";
}
});
</script>
</body>
</html>

Related

Trying to take input from HTML and do computation with it in Javascript

I’m trying to get the computer to take an input from the HTML and add and multiply some number to it in Javascript. I’m from python and the variable system in Javascript makes no sense to me, so can someone please lmk what to do?
<div class = "text">How much energy do you use?</div>
<input id = "q1" type = "text" placeholder = "# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<!-- Multiply InputValue by 3 and Add 2 —->
I tried to do something with parseInt, and parseString, but it didn’t work as it would just not run.
try this, first query input value then calculate your desire numbers then alert the user,
like this <!-- Multiply InputValue by 3 and Add 2 —->
function getInputValue() {
const inputVal = document.getElementById("q1").value; //query input value
const calculatedValue = ((inputVal *3) +2); // first multiply input value with 3
// then add 2
alert(calculatedValue); // show the calculated value through an alert
};
It's not that hard. try to play with the below code. Cheers!!
<html>
<body>
<label for="insertValue">Enter Your Value:</label>
<input type="text" id="insertValue">
<button onclick="Multiply()">Multiply</button> <!-- Calling to the JS function on button click -->
<p id="answer"></p>
<!-- Always link or write your js Scripts before closing the <body> tag -->
<script>
function Multiply() {
let value = document.getElementById("insertValue").value; //get the inserted Value from <input> text box
let answer = 0;
//Your Multiplication
answer = value * 2 * 3;
//Display answer in the <p> tag and it id ="answer"
document.getElementById("answer").innerText = "Your Answer is: "+ answer;
}
</script>
</body>
</html>
Easy (to understand) Solution:
<div class="text">How much energy do you use?</div>
<input id="q1" type="text" placeholder="# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<br>
<output id="a1"></output>
<script>
var input = document.getElementById("q1");
var output = document.getElementById("a1");
function getInputValue() {
output.textContent = (input.value * 3) + 2;
}
</script>

3 text box Math in Javascript

Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim

How do I get my javascript var to return in an html paragraph?

I'm writing a simple function just for fun for a friend, but my js function wont return x the way I want it.
I have a text field and a button. If a user inputs "no good lyer" x should return "Big Fucking Surprise!"
If a user inputs anything else with text, x should return "Leave her ass anyway!"
If a user doesn't input anything x should return "Make a decision!"
Here is my code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a decision about your ex.</p>
<p id="choice">Here is your Decision</p>
<form>
My Ex:<input type="text" name="myEx">
</form>
<button onclick="myLife()">Decide</button>
<script>
function myLife()
{
var x="";
if("myEx".text=="no good lyer")
{
x="Big Fu**ing Surprise!";
}
if("myEx".text!="no good lyer")
{
x="Leave her a** anyway!";
}
if("myEx".text=="")
{
x="Make a decision!"
}
document.getElementById("choice").innerHTML=x
}
</script>
</body>
</html>
Sorry but javascript strings don't have methods called text. your trying to get the value of the input <input type="text" name="myEx"> with 'myEx'.text, which is strange to say the least but you need to use normal people javascript. try getElementsByName('myEx')[0]
Add this variable to the top of your function myLife:
var myEx = document.getElementsByName('myEx')[0].value
change every line like this:
"myEx".text
to simply this
myEx
First of all you should use === and !== operator to check for conditions, Try the code below
To get a value from a input text use .value
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a decision about your ex.</p>
<p id="choice">Here is your Decision</p>
<form>
My Ex:<input type="text" id="myText" value="">
</form>
<button onclick="myLife()">Decide</button>
<script>
function myLife()
{
var myText = document.getElementById("myText");
var x="";
if(myText.value==="no good lyer")
{
x="Big surprise!";
}
if(myText.value!=="no good lyer")
{
x="Leave her!";
}
if(myText.value === "")
{
x="Make a decision!"
}
document.getElementById("choice").innerHTML=x
}
</script>
</body>
</html>
change your script to following
<script>
function myLife()
{
var x="";
if("myEx".text=="no good lyer")
{
x="Big Fu**ing Surprise!";
}
if("myEx".text!="no good lyer")
{
x="Leave her a** anyway!";
}
if("myEx".text==null)
{
x="Make a decision!"
}
document.getElementById("choice").innerHTML=x
}
</script>

Build, Modify, Output Javascript Array

I'm trying to accomplish the following...if it's asking too much in a single question then some simple steps on what events to use will still help.
There are 2 blank textareas sitting next to eachother - Input and Output. Between them are two inputs Before and After. I want to type or paste a list of words into Input separated by line break, for example:
melons
peaches
apples
And then use the Before and After inputs to add in a word/phrase/symbol before and after each keyword. So if I type 'buy' in before and 'today' in after, the Output text area will display:
buy melons today
buy peaches today
buy apples today
I'd like to accomplish this without having any page refreshing. We can assume the form elements are named as follows:
<textarea id="input"></textarea>
<input type="text" id="before" />
<input type="text" id="after" />
<textarea id="output"></textarea>
I've been try to at least get the Input text to display in Output using this code, but that's not even working:
$(document).ready(function(){
$('#input').keyup(function(e){
$('#output').html($(this).val());
});
});
Any guidance would be awesome!
a compact one:
$("#input,#before,#after").on("keyup", function () {
$("#output").val(
$.map($("#input").val().split("\n"), function (n, i) {
return $("#before").val() + " "+ n + " " + $("#after").val();
}).join("\n"));
});
example
This would do the trick:
function update_output(){
//Split input by newline
var input_words = $('#input').val().split('\n');
var output_lines = new Array();
//Iterate over each keyword and prepend and append values
$.each(input_words, function(i, word){
output_lines.push($('#before').val()+' '+word+' '+$('#after').val());
});
//Display output in textarea
$('#output').val(output_lines.join('\n'));
}
You just need to choose when you want to update the output textarea, maybe bind it so it updates every time the #input or #before and #after changes:
$('#input,#before,#after').on('change',update_output);
Alright, I can help you to get started. My answer is not complete, but you can have a very good idea from here. Note I wrote this code to be easy to understand and I am not using sophisticated approaches on purpose.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#input").keypress(function(key){
if(key.which == 13) {
refreshData();
}
});
});
function refreshData() {
var beforeVal = $("#before").val();
var inputLines = $("#input").val().split(/\r\n|\r|\n/g);
var desiredOutputVal = "";
for(var i=0; i<inputLines.length; i++) {
desiredOutputVal += beforeVal + inputLines[i] + "\n";
}
$("#output").val(desiredOutputVal);
}
</script>
</head>
<body>
<form>
<textarea id="input"></textarea>
<input type="text" id="before" />
<input type="text" id="after" />
<textarea id="output"></textarea>
</form>
</body></html>

Javascript calculator as users type numbers

I'm a noob at Javascript, but I'm trying to implement something on my website where users can type a quantity, and the subtotal updates dynamically as they type.
For example: if items are 10 dollars each, and a user types 5 in the text field I would like it to show $50 next to the text box. Pretty simple multiplication, but I don't know how to do it with Javascript. I think onKeyPress somehow? Thanks!
Assuming the following HTML:
<input type="text" id="numberField"/>
<span id="result"></span>
JavaScript:
window.onload = function() {
var base = 10;
var numberField = document.getElementById('numberField');
numberField.onkeyup = numberField.onpaste = function() {
if(this.value.length == 0) {
document.getElementById('result').innerHTML = '';
return;
}
var number = parseInt(this.value);
if(isNaN(number)) return;
document.getElementById('result').innerHTML = number * base;
};
numberField.onkeyup(); //could just as easily have been onpaste();
};
Here's a working example.
You should handle 'onkeyup' and 'onpaste' events to ensure you capture changes by keyboard and via clipboard paste events.
<input id='myinput' />
<script>
var myinput = document.getElementById('myinput');
function changeHandler() {
// here, you can access the input value with 'myinput.value' or 'this.value'
}
myinput.onkeyup = myinput.onpaste = changeHandler;
</script>
Similarly, use getElementById and the element's innerHTML attribute to set the contents of an element when you want to show the result.

Categories

Resources