Compare a user inputted number with a randomly generated number in Javascript - javascript

I want to create a randomly generated number, ask the user to enter a number, then compare the two and then show a popup telling whether or not they match. This is my code
function myFunction() {
var num=document.getElementById("demo").innerHTML = Math.floor(1000 + Math.random() * 9000);
}
function myFunction1() {
var secondInput = document.getElementById("demo1").value;
if( num === secondInput)
{
window.alert("Same");
}
else
{
window.alert("Don't do that again cvv");
}
<button onclick="myFunction()">press the button to see the code</button>
<p id="demo"></p>
code: <input type="text" name="code" required/><br/><br/>
<button onclick="myFunction1()">Compare</button>
<p id="demo1"></p>

This code works. Please know that there were a couple of improvements:
You referenced to myFunction() before the javascript is loaded.
You need to keep the var num in global scope if you want to reference it in other places, without passing them as an argument.
When comparing values, make sure to select the right input field and to convert the value string to a Number.
var num;
function myFunction() {
num=document.getElementById("demo").innerHTML = Math.floor(1000 + Math.random() * 9000);
}
document.getElementById("button1").addEventListener('click', myFunction)
document.getElementById("button2").addEventListener('click', myFunction1)
function myFunction1() {
var secondInput = document.getElementById("demo1").value;
if( num === +secondInput) {
window.alert("Same");
}
else {
window.alert("Don't do that again cvv");
}
}
<button id="button1" >press the button to see the code</button>
<p id="demo"></p>
code: <input id="demo1" type="text" name="code" required/><br/><br/>
<button id="button2">Compare</button>
<p></p>

First you have to define num in the global scope to be accessable by the two functions and you have to make the first function just show the number without generating a new number every time.
var num;
function show() {
document.getElementById("demo").innerHTML = num;
}
function randomizeAndCompare() {
num = Math.floor(1000 + Math.random() * 9000);
var secondInput = document.getElementById("demo1").value;
if( num === secondInput){
window.alert("Same");
}
else{
window.alert("Don't do that again cvv");
}
}
<button onclick="show()">press the button to see the code</button>
<p id="demo"></p>
code: <input type="text" name="code" required/><br/><br/>
<button onclick="randomizeAndCompare()">Compare</button>
<p id="demo1"></p>

There are a couple of tings here.
First, myFunction1() isn't closed. You should also rename it to something more meaningful, like "compareValue()". That way it is easier to read the code.
You also aren't making a comparison of the two numbers in your compareValue()-function. Your 'num' variable isn't defined. You are also trying to extract the user input value from the button.
See my suggestion for changes:
function generateRandom() {
document.getElementById("demo").innerHTML = Math.floor(1000 +
Math.random() * 9000);
}
function compareValues() {
var num = document.getElementById("demo").innerHTML;
var input = document.getElementById("number").value;
if( num === input)
{
window.alert("Same");
}
else
{
window.alert("Don't do that again cvv");
}
}
HTML:
<button onclick="generateRandom()">press the button to see the code</button>
<p id="demo"></p>
code: <input id="number" type="text" name="code" required/><br/><br/>
<button onclick="compareValues()">Compare</button>
<p id="demo1"></p>

Related

Math.pow(x,y) isnt working when used with document.getElementById('z').value

Was trying to use Math.pow(x,y) on two values inputted in an HTML tag, for some reason it ain't working.
Input1: <input id="input1"> Input2: <input id="input2">
<button onlick="myFunction()">Click Me!</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById('input1').value;
var y = document.getElementById('input2').value;
var z = Math.pow(x, y);
document.getElementById("demo").innerHTML = +z;
}
</script>
You had a typo in your onclick handler attribute. It should be "onclick" not "onlick". Also, you should add the type="number" attribute to your inputs so that users can't enter non-numbers. Furthermore, you should explicitly parse the input values into integers using the parseInt function rather than relying on JS's implicit conversions. Full working example:
function myFunction() {
var xText = document.getElementById('input1').value;
var yText = document.getElementById('input2').value;
var xNum = parseInt(xText, 10);
var yNum = parseInt(yText, 10);
var z = Math.pow(xNum, yNum);
document.getElementById("demo").innerHTML = z;
}
Input1: <input id="input1" type="number">
Input2: <input id="input2" type="number">
<button onclick="myFunction()">Click Me!</button>
<p id="demo"></p>
It's onclick and not onlick which you had mistakenly typed in your code. Do note that you would get NaN as the output if either of the input by user is not in integer format.
So, you can either mention type = 'Number' while taking input explicitly or make a check function which would give an error prompt to user if the input is not a number. I have included a format check function in the demo below.
The below code works after the correction -
<!DOCTYPE html>
<html>
<body>
Input1: <input id="input1"> Input2: <input id="input2">
<button onclick="myFunction()">Click Me!</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById('input1').value;
var y = document.getElementById('input2').value;
if (isNaN(x) || isNaN(y)) {
document.getElementById("demo").innerHTML = 'Wrong input format';
} else {
var z = Math.pow(x, y);
document.getElementById("demo").innerHTML = +z;
}
}
</script>
</body>
</html>

How to check and return a message if no value entered

I'm still learning and am trying to simply take a number from an input, add 7 to it, and then display it on the webpage. It all works fine, but what I don't like is if you hit "submit" without entering a number, the HTML field shows "NaN" vs. a custom message, which is what I'd like to do.
Here's the code I have so far. What am I missing to capture that nothing was entered and return a different message?
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
if (isNaN(number)){
document.getElementById("add").innerHTML ="Please enter a value";
}
else {
let original = parseInt(number,10);
num = addition + original;
document.getElementById("add").innerHTML = num;
}
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add"></p>
</div>
That is because an empty string actually returns true when passed to isNaN(), i.e. isNaN('') returns true.
To do that, you can simply move the check to the final step, a.k.a. evaluate the num variable instead:
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
let original = parseInt(number, 10);
let num = addition + original;
if (isNaN(num)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>
Alternatively, you can also simply parse the input element's value directly: it will inform you if it is not a number right away:
function add7() {
let number = parseInt(document.getElementById('num').value, 10);
if (isNaN(number)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
let addition = 7;
let num = addition + number;
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>

How to handle an input parameter in javascript

I wrote a code to change values in Fahrenheit to Celsius using Javascript.
<p id = "result"> </p> // The result will appear here
<script>
function toCelsius(f) {
return (f-32) * 5/9;
}
document.getElementById("result").innerHTML = toCelsius(77);
</script>
I checked this code, and it works on my Eclipse.
However, instead of putting the value directly, I want to input a number in Fahrenheit and change that into Celsius.
I added the following.
<form id="frm1">
Enter a number : <input type="text" name=fahrenheit> <br>
<input type=button" onclick="toCelsius(frm1)" value="change"> // I need some help for handling parameter here
</form>
I want to make it as simple as possible like below.
Could anyone give me some tips on how to handle an input parameter?
I spotted a few problems.
There were some syntax issues in writing HTML attributes
The code that changes innerHTML of result won't get invoked when the button is clicked. Rather, it'll get invoked only once, the first time the script is run. To fix this, I placed that line in a function which would be called when the button is clicked. Please look at the change button action.
<p id="result"></p>
<script>
function toCelsius(f) {
return (f - 32) * 5 / 9;
}
function changeClicked() {
var input = document.getElementById("fahrenheit").value;
if (parseInt(input) === null) return;
document.getElementById("result").innerHTML = toCelsius(input);
}
</script>
<form id="frm1">
Enter a number : <input type="text" id="fahrenheit" name="fahrenheit"> <br>
<input type="button" onclick="changeClicked()" value="change">
</form>
Add an event listener for the button then call your toCelsius() function with passing the input value to it.
function toCelsius(f) {
return (f - 32) * 5 / 9;
}
document.getElementById('btn_change').addEventListener('click', function() {
var fahrenheit = document.getElementsByName('fahrenheit')[0].value;
document.getElementById('result').innerHTML = toCelsius(fahrenheit);
});
<form id="frm1">
Enter a number : <input type="text" name=fahrenheit> <br>
<input type="button" id="btn_change" onclick="toCelsius(frm1)" value="change">
</form>
<p id="result"> </p>
// Give input tag an id of "number"
Enter a number : <input type="text" name=fahrenheit id ="number"> <br>
// Then,
<script>
let number = document.getElementById("number").value;
function toCelsius(f) {
return (f-32) * 5/9;
}
document.getElementById("result").innerHTML = toCelsius(number);
</script>
<!-- The result will be displayed here -->
<p id="result" style="min-height: 20px"></p>
<input type="number" name="fahrenheit">
<input type="button" class="convert-to-celsius-btn" value="Convert to C">
<script>
var convertBtn = document.querySelector(".convert-to-celsius-btn");
var fahrenheitInput = document.querySelector("input[name=fahrenheit]");
var resultEl = document.querySelector("#result")
function toCelsius(f) {
return (f-32) * 5/9;
}
function convertToCelsius() {
var fahrenheit = fahrenheitInput.value;
// input validatation code goes here ...
// next convert to celsius
var celsius = toCelsius(fahrenheit)
// now show the value in the DOM
celsius = celsius.toFixed(2);
resultEl.textContent = celsius + " C"
}
convertBtn.addEventListener("click", convertToCelsius);
</script>

See length of value in text box

I want to be able to type a word into the text box and then click a button underneath which will issue an alert if the number of letters is below 5.
Type in words to see how long they are: <input type="text" id="txtBox" name="txtBox" value="banter"/>
<button onclick="myFunction()">Try It</button>
<script type="text/javascript">
function myFunction() {
var x = document.getElementById['txtBox'];
if (x.length < 5) {
alert('please enter at least 5 characters');
return false;
}
}
</script>
Here x is an element not a value
So change the x.length to x.value.length
Type in words to see how long they are: <input type="text" id="txtBox" name="txtBox" value="banter"/>
<button onclick="myFunction()">Try It</button>
<script type="text/javascript">
function myFunction() {
var x = document.getElementById('txtBox');
if (x.value.length < 5) {
console.log(x.length);
alert('please enter at least 5 characters');
}
}
</script>
Make your var x = document.getElementById['txtBox']; to var x = document.getElementById('txtbox');
Two things: functions are called with (), not [], and you need to check the length of the element's value rather that of the element itself.
function myFunction() {
var element = document.getElementById('txtBox');
if (x.value.length < 5) {
alert('please enter at least 5 characters');
return false;
}
}
Please, make the following change in your code and it will work:
var x = document.getElementById('txtBox').value;

Saving a Value, and adding to it

There are a few ways this can be asked, I'm trying to go with the easiest. Basically, I have two fields... one is to add a number, the other is to subtract. What I want, is when a number is input into either (let's just stick with the add input for now) and have it update at the bottom once the button "+" is pressed. I want that result to stay at the bottom, so when a new value is put into the add box and the button is pressed, it ADDS to the previous total. For the life of me, I can't figure this one out. Once resolved, I'll take care of the subtraction on my own, just need a push in the right direction. The current code is as follows.
<div id="entire">
<div id="content">
<input type="number" id="addInput" placeholder="0">
<button type="button" id="addBtn" onclick="add()">+</button>
<br>
<br>
<input type="number" id="subInput" placeholder="0">
<button type="button" id="subBtn" onclick="sub()">-</button>
<br>
<br>
<div id="totalAmt"></div>
<br>
<input type="button" id="clear" onclick="clearFields()" value="Clear">
<input type="button" id="reset" onclick="reset()" value="Reset">
</div>
</div>
function add() {
var addInput = document.getElementById("addInput").value;
var emptyValue = "";
var total = emptyValue + addInput;
document.getElementById("totalAmt").innerHTML = total;
}
function clearFields() {
document.getElementById("addInput").value = "";
document.getElementById("subInput").value = "";
}
function reset() {
document.getElementById("totalAmt").innerHTML = "";
}
A link to my codepen is below:
http://codepen.io/0ktane/pen/NNdbOq
Your problem is these two lines
var emptyValue = "";
var total = emptyValue + addInput;
when you are concatenating to a string, you get a string back.
Also, you are not even considering the previous value at first place.
Try this, updated pen
function add() {
var addInput = parseInt(document.getElementById("addInput").value); //parse the value to an integer first
var totalAmt = parseInt(document.getElementById("totalAmt").innerHTML); //parse the value to an integer first
totalAmt = isNaN(totalAmt) ? 0 : totalAmt; //if the value is NaN(not a number) reset it to 0
addInput = isNaN(addInput) ? 0 : addInput;//if the value is NaN(not a number) reset it to 0
document.getElementById("totalAmt").innerHTML = totalAmt + addInput ; //output the correct value
}
var total = 0;
function add() {
var addInput = parseInt(document.getElementById("addInput").value);
total = total + addInput;
document.getElementById("totalAmt").innerHTML = total;
}

Categories