Button not working, with .addEventListener - javascript

I'm creating simple HTML programs with JavaScript. The buttons aren't working when I click on it. Here is my code:
index.html
<!DOCTYPE html>
<html>
<body>
<h1> A random machine</h1>
<p>
Include floating-point number
</p>
<p>
Want an integer? Click here!
</p>
<button id="integerChanges" type="button"> Click me! </button>
<p>
Enter an integer/floating-point number here (start point, included):
<input placeholder="Random number" id="a">
</p>
<br>
<p>
Enter another integer/floating-point number here (end point, not included):
<input placeholder="Random number" id="b">
</p>
<button id="submit"> Submit </button>
<script>
document.getElementById("submit").addEventListener("click", function() {callX()})
document.getElementById("integerChanges").addEventListener("click", function() {
window.location.href="integer.html"
})
a = document.getElementById("a")
b = document.getElementById("b")
a.parseInt()
b.parseInt()
if (a > b) {
throw "start point > end point "
window.location.href="retakeHandler.html"
}
function callX() {
var x = Math.random(document.getElementById("a"), document.getElementById("b"));
console.log(x);
document.querySelector("html").innerHTML = x;
};
function callX2() {
var x2 = Math.floor((Math.random(a,b)) * 10 + 1);
document.querySelector("html").innerHTML = x2;
};
function retakeForm_error() {
var buttonRetake = document.createElement
}
</script>
</body>
</html>
integer.html
<!DOCTYPE html>
<html>
<body>
<h1> A random machine</h1>
<p>
Include floating-point number
</p>
<p>
Want an integer? Click here!
</p>
<button id="integerChanges" type="button"> Click me! </button>
<p>
Enter an integer/floating-point number here (start point, included):
<input placeholder="Random number" id="a">
</p>
<br>
<p>
Enter another integer/floating-point number here (end point, not included):
<input placeholder="Random number" id="b">
</p>
<button id="submit"> Submit </button>
<script>
document.getElementById("submit").addEventListener("click", function() {callX()})
document.getElementById("integerChanges").addEventListener("click", function() {
window.location.href="integer.html"
})
a = document.getElementById("a")
b = document.getElementById("b")
a.parseInt()
b.parseInt()
if (a > b) {
throw "start point > end point "
window.location.href="retakeHandler.html"
}
function callX() {
var x = Math.random(document.getElementById("a"), document.getElementById("b"));
console.log(x);
document.querySelector("html").innerHTML = x;
};
function callX2() {
var x2 = Math.floor((Math.random(a,b)) * 10 + 1);
document.querySelector("html").innerHTML = x2;
};
function retakeForm_error() {
var buttonRetake = document.createElement
}
</script>
</body>
</html>
retakeHandler.html
<!DOCTYPE html>
<html>
<body>
<h1>
Error: start point > end point
</h1>
<p id="retakeForm"></p>
<script>
function retake() {
var myP = document.getElementById("retakeForm");
// creating button element
var button = document.createElement('BUTTON');
// creating text to be
//displayed on button
var text = document.createTextNode("Click me");
// appending text to button
button.appendChild(text);
// appending button to div
myP.appendChild(button); ;
}
</script>
</body>
</html>
Edited many versions (this is version 3 or 4 now) and added files
Public on Repl.it with name: ElectronicFatherlySale
Notes:
Code isn't done
Please help me and explain why this happens?

I see few small mistakes in your code:
document.getElementById("a") = a; does not mean anything, because you are trying to set a value to something cannot be modified
You have declared two functions, callX and callX2, but you never call them. I suggest you to do the following first:
--
<script>
document.getElementById("submit").addEventListener("click", function () {
callX();
callX2();
})
function callX() {
var x = Math.random(document.getElementById("a"), document.getElementById("b"));
console.log(x);
document.querySelector("html").innerHTML = x;
};
function callX2() {
document.getElementById("integerChanges").addEventListener("click", function () {
var x2 = Math.floor((Math.random(a, b)) * 10 + 1);
document.querySelector("html").innerHTML = x2;
})
};
</script>

Related

Local storage example doesn't work how I expect it to be

In my Web university course there is this example with local storage and it says it should show in the input area the number of clicks on the button and also store it in localstorage, but all I get is NaN on the input no matter how many times I click on the button.
<head>
<script>
window.onload = function()
{
var el=document.getElementById("bt");
el.onclick= function()
{
var x = parseInt(localStorage.getItem("nrc"));
if (x!==NaN){
localStorage.setItem("nrc", x + 1);
}
else{
localStorage.setItem("nrc", "1");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
document.getElementById("write").value = localStorage.getItem("nrc");
var buton2=document.getElementById("bt2");
buton2.onlick = function ()
{
localStorage.removeItem("nrc");
}
}
</script>
</head>
<body>
<p> Number of clicks on the button <input type="text" id="write" value="0"> </p>
<button id="bt"> Click</button>
<button id="bt2"> Click2</button>
</body>
Edit: problem was solved, but now if i want to remove an item from local storage or clear the localstorage it doesn't work.
You have a typo, you wrote onlick instead of onclick
buton2.onclick = function() {
console.log('clearing storage!');
localStorage.removeItem("nrc");
// Reset input back to zero
document.getElementById("write").value = '0';
}
Complete working example here
You were checking a non number to a non number which will always true.
Anyways the solution is already posted in the comments
<head>
<script>
window.onload = function() {
var el = document.getElementById("bt");
el.onclick = function() {
var x = parseInt(localStorage.getItem("nrc"));
if (!isNaN(x)) {
localStorage.setItem("nrc", x + 1);
} else {
localStorage.setItem("nrc", "1");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
</script>
</head>
<body>
<p> Number of clicks on the button <input type="text" id="write" value="0"> </p>
<button id="bt"> Click</button>
</body>

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>

Compare a user inputted number with a randomly generated number in 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>

i can not understand why my code is not being executed

I have three buttons below and the button marked +1, should increment wallet by one. The button marked Transfer money to Bank should move wallet amount to bank and reset wallet to 0. But, nothing is being called or working. I am absolutely stuck. Please help.
<html>
<head>
<title>Area 52</title>
</head>
<body>
<h1><center>Area 52</center></h1>
<p><center><p Id="name">User</p><p>Is currently logged on</p></center><p>
<script>
var money=0
var bank=0
var Money_handler(money,bank,op){
alert("!")
if (op=="add"){
money+=1
document.getElementById('wallet').innerHTML = money;
return money;
}
if (op=="bank"){
bank=bank+money
document.getElementById('bank').innerHTML = bank;
money=0
document.getElementById('wallet').innerHTML = money;
return money
}
}
var namer=function(){
var x=prompt("What is your name?");
document.getElementById('name').innerHTML = x;
}
</script>
<center>
<button type="button" onclick=money=Money_handler(money,bank,"add")>+1</button>
<button type="button" onclick=namer()>Enter username</button>
<button type="button" onclick=Money_handler(money,bank,"bank")>Transfer money to Bank</button>
<p Id="wallet">Wallet: $0</p>
<p Id="bank">Bank: $0</p>
</center>
</body>
</html>
You just use a var instead of a function:
function Money_handler(money,bank,op){
EDIT:
When you update the money you forget the rest of the line:
.innerHTML = "Wallet: $"+money;
You had to change this at all 3 places with wallet/bank.
This should work. Aside from the function keyword, you also missed quotes for the onclick attribute value.
<html>
<head>
<title>Area 52</title>
</head>
<body>
<h1><center>Area 52</center></h1>
<p><center><p Id="name">User</p><p>Is currently logged on</p></center><p>
<script>
var money = 0
var bank = 0
var Money_handler= function(money, bank, op) {
alert("!")
if (op == "add") {
money += 1
document.getElementById('wallet').innerHTML = money;
return money;
}
if (op == "bank") {
bank = bank + money
document.getElementById('bank').innerHTML = bank;
money = 0
document.getElementById('wallet').innerHTML = money;
return money
}
}
var namer = function() {
var x = prompt("What is your name?");
document.getElementById('name').innerHTML = x;
}
</script>
<center>
<button type="button" onclick="Money_handler(money,bank,'add');">+1</button>
<button type="button" onclick="namer()">Enter username</button>
<button type="button" onclick="Money_handler(money,bank,'bank')">Transfer money to Bank</button>
<p Id="wallet">Wallet: $0</p>
<p Id="bank">Bank: $0</p>
</center>
</body>
</html>
Note: I only corrected the syntactical flaws. I think you should work on logic.

How to change field on HTML file when button is pressed

How do I change the HTML itself when I press a button? When I press a button in this case, the value is stored as "displayCount". Is there a way in which I can directly see the count on the HTML code? If it was press one time, I could see the number 1 on the HTML itself, not as a variable?
Thank you!
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title> </title>
</head>
<body>
<input type="button" value="Count" id="countButton" />
<p>The button was pressed <span id="displayCount">0</span> times.</p>
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function() {
count++;
display.innerHTML = count;
}
</script>
</body>
</html>
For example, if button was pressed once, one of the line would change from
<p>The button was pressed <span id="displayCount">1</span> times.</p>
This Fiddle works as you want..
i changed your script into :
var count = 0;
function countIt(){
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
count++;
display.innerHTML = count;
}
and your HTML to :
<input type="button" onclick="countIt()" value="Count" id="countButton" />
<p>The button was pressed <span id="displayCount">0</span> times.</p>
hope this will help you
<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="onClick()">Count</button>
<p>The button was pressed : <a id="clicks">0</a></p>
Here is my jsfiddle to your problem.
I delete the varible count you used, and just use the number on your HTML, it works well.
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function(){
display.innerHTML = ++display.innerHTML;
}
Thanks,
Edison
I guess you might want to use parseInt() explicitly increment the count as an integer like this:
var count = parseInt(display.textContent,10);
Your code could go like this:
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
var count = parseInt(display.textContent,10);
button.onclick = function(){
count++;
display.innerHTML = count;
}
DEMO : http://jsfiddle.net/naokiota/9dQjv/2/
The document of the parseInt() is here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
Hope this helps.
<script>
var count = 0;
function counts()
{
var result = document.getElementById('txtbxid');
count ++ ;
result.value = count;
}
</script>
<input type="text" id="txtbxid" name="txtbxid">
<input type="button" id="add" name="add" value="add" onClick="counts()">

Categories