nothing happens when I click button - javascript

I am trying to make a simple webpage where the user enters in a number and the page tells the user whether the number they entered in is even or odd. I would like to display that in the textbox at the bottom of the screen.
However, when I click the button, nothing happens. I even tried to add an "alert" when the button is pressed, but even that doesn't happen. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Compute the factors of a positive integer</title>
<script type = "text/javascript">
function oddOrEven(){
var userInput = document.getElementById('number');
var number = number.value;
var output = document.getElementById('display');
alert(number);
if(number % 2 == 0){
output.value = number + " is even!"
}else{
output.value = number + " is odd!"
}
}
</script>
</head>
<body>
<form>
Enter a number to check whether it is odd or even: <input type = "text" id = "number"><br>
<button type="button" onclick="oddOrEven()">Click here to check!</button>
<input type = "text" id = "display">
</form>
</body>
</html>

Take a look at these three lines here:
var userInput = document.getElementById('number');
var number = number.value;
alert(number);
You've retrieved a reference to the #number element and stored it in the userInput variable. Then, you've created a variable called "number," but the value you assigned to it is a property of the variable you just created.
However, this object reference stored in the number variable doesn't have this property, which is causing a runtime error. Try pressing F12 while in your browser with this script running and see what errors appear in the console.
Instead, try this out and see what reaction you get:
var userInput = document.getElementById('number');
var number = userInput.value;
number = parseInt(number);

I see a couple typos in your code, here's a modified version that I think ought to work:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Compute the factors of a positive integer</title>
<script type = "text/javascript">
function oddOrEven(){
var userInput = document.getElementById('number');
var number = userInput.value; // you originally had "number.value", but that doesn't make any sense.
number = parseInt(number); // number is initialy a string, we need to convert it to an integer
var output = document.getElementById('display');
alert(number);
if(number % 2 == 0){
output.value = number + " is even!"
}else{
output.value = number + " is odd!"
}
}
</script>
</head>
<body>
<form>
Enter a number to check whether it is odd or even: <input type = "text" id = "number"><br>
<button type="button" onclick="oddOrEven()">Click here to check!</button>
<input type = "text" id = "display">
</form>
</body>
</html>

You've made a mistake.
You wrote:
var number = number.value;
You should have written:
var number = userInput.value;

Related

Button function calling another function

im just a beginner and i want to find the answer to this problem.
This is my html code.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name = "step" id = "step">
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>
This is my javascript code.
var step = document.getElementById("step").innerHTML;
parseInt(step);
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one += 5;
num++;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
What I did is to call the function matchHouses(step) by the click of the button. But the output is always 1. I also put parseInt to the step id as it is string but it is still doesnt work. I was expecting an output of 1+5 if the input is 1, 1+5+5 if the input is two and so on. How do I make it work?
The two key things are that a) parseInt won't do the evaluation "in place". It either needs to be assigned to a variable, or the evaluation done as you're passing it into the matchHouse function, and b) you should be getting the value of the input element, not the innerHTML.
Here are some additional notes:
Cache all the elements first.
Add an event listener in your JavaScript rather than using inline JS in the HTML.
No need to have an additional variable for counting - just decrement step until it reaches zero.
Number may be a more suitable alternative to parseInt which requires a radix to work properly. It doesn't always default to base 10 if you leave it out.
Assign the result of calling the function to demo's textContent (not innerHTML as it is just a simple string, and not a string of HTML markup.
// Cache elements
const step = document.querySelector('#step');
const demo = document.querySelector('#demo');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', handleClick);
function matchHouses(step) {
let out = 1;
while (step > 0) {
out += 5;
--step;
}
return out;
}
function handleClick() {
// Get the value of the input string and
// coerce it to a number
const n = Number(step.value);
demo.textContent = matchHouses(n);
}
<body>
<input type="text" name="step" id="step">
<button type="button">Submit</button>
<p id="demo"></p>
</body>
I rewrote your code like this:
let step = 0;
function handleInput(e){
step = e.value;
}
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one += 5;
num++;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name="step" id="step" onkeyup='handleInput(this)'>
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>

Automatic change of input fields through Event Handler "onkeyup"

I am pretty bad at JS but I need some help at a task in order to prepare for a small exam on web technology.
The task:
I have to write a code where two input fields have to be displayed. The sum of both of the input fields have to be 100. So the input fields will be mainly used for typing in some numbers.
When I type a number in the first input field between 0 - 100 there should be displayed the remaining amount of 100 in the second input field after typing the last number of the first number. This should be also working vice versa. So it should be irrelevant which input field I type in the number. Our professor suggests us to use the event handler "onkeyup".
One example:
First Input field: 3 -> typed in
Second Input field: 97 -> will be shown automatically after typing 3
Please don't laugh, here is my code:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script>
function calc() {
var firstnum = document.getElementById("firstprop").value;
var secondnum = document.getElementById("secondprop").value;
var firstresult = 100 - parseInt(secondnum);
var secondresult = 100 - parseInt(firstnum);
if(firstnum >=0){
secondnum = secondresult;
}
if(secondnum >=0){
firstnum = firstresult;
}
}
</script>
<head>
<body>
<input type="text" onkeyup="calc()" id="firstprop"/>
<input type="text" onkeyup="calc()" id="secondprop"/>
</body>
</html>
Thank you very much for your help. I appreciate it, really :)
Here you are
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script>
function calc(value, index) {
if (index == 1) {
document.getElementById("secondprop").value = 100 - value;
} else if (index == 2) {
document.getElementById("firstprop").value = 100 - value;
}
}
</script>
<head>
<body>
<input type="text" onkeyup="calc(this.value, 1)" id="firstprop" />
<input type="text" onkeyup="calc(this.value, 2)" id="secondprop" />
</body>
</html>
function calc(e) {
if (e.target.id === "firstprop") {
var secondElement = document.getElementById("secondprop");
var value1 = e.target.value ? e.target.value : 0;
secondElement.value = 100 - (parseInt(value1));
}
if (e.target.id === "secondprop") {
var secondElement = document.getElementById("firstprop");
var value2 = e.target.value ? e.target.value : 0;
secondElement.value = 100 - (parseInt(value2));
}
}
</script>

Pixel to cm conversion script not working

The goal is to type in one text box a certain value (of pixels or centimeters) then to press a button, and the button to do some maths and show the result in a different text box.
What happens is, I'll get a result of 'NaN', implying that the string I inputted hadn't been converted properly. I've gone through hundreds of methods to fix this and it still doesn't work.
Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Conversion</title>
</head>
<body bgcolor=#FF0000>
<form id="conversions" name="conversions">
Pixel value :
<br>
<input type="text" name="pxvalue" id="pxvalue">
<br>
<input type="submit" name="convertcm" id="convertcm" value="Convert cm to px!">
<input type="submit" name="convertpx" id="convertpx" value="Convert px to cm!">
<br>Centimeter value :
<br>
<input type="text" name="cmvalue" id="cmvalue">
<br>
<br>Output :
<input type="text" name="output" id="output">
</form>
<!-- This is where all the JavaScript code goes -->
<script>
var form = document.getElementById("conversions");
var strcmvalue = form.elements["cmvalue"];
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue);
var pxvalue = ToInteger(strpxvalue);
var output = document.getElementById("output");
var ccmbutton = document.getElementById("convertcm").onclick = cm_to_pixel_conversion(cmvalue);
var cpxbutton = document.getElementById("convertpx").onclick = pixel_to_cm_conversion(pxvalue);
var cm_per_pixel = 0.026458333;
var px_per_cm = 37.795275591;
function pixel_to_cm_conversion(pvalue) {
cmconversion = pvalue / px_per_cm;
output.value = cmconversion.toString();
}
function cm_to_pixel_conversion(cvalue) {
pxconversion = cvalue / cm_per_pixel;
output.value = pxconversion.toString();
}
function ToInteger(x) {
x = Number(x);
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
</script>
<!-- End of the JavaScript code-->
</body>
</html>
Because you are not passing a value to the method, you are passing an html element.
var strcmvalue = form.elements["cmvalue"]; //reference element
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue); //passing element, not the value
var pxvalue = ToInteger(strpxvalue);
You need strcmvalue.value or form.elements["cmvalue"].value
Next issue is the fact you read the values when the page loads, so you will only ever have the values from the time it loads.
So you should be reading the values and converting them to numbers inside of your methods, not when the page loads.
After that your click event is calling the function, not referencing it.
var ccmbutton = document.getElementById("convertcm").onclick = function () {
var num = parseInt(strcmvalue.value, 10);
cm_to_pixel_conversion(num);
return false;
};

Input field not updating

I am trying to create a tip calculator using HTML and Javascript and each time the user changes the input field for the meal cost and tip amount, I have to validate whether or not it is a number and if it is, I have to cut down the number to 2 decimal places.
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = mealCost.toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = tipPercent.toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge);
var tipPercentage = document.getElementById(tipPercent);
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
I don't think it is taking the values that are edited using toFixed() and also the field tipAmount is showing NaN. How can I fix these errors?
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = parseInt(mealCost).toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = parseInt(tipPercent).toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge).value;
var tipPercentage = document.getElementById(tipPercent).value;
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
The validateMealCost and validateTipPercent functions lacked a parseInt to turn the values to numbers, and the calculateTipAmount function lacked a .value, turning it to NaN.
you need to parse the inputs - all the text inputs will provide strings and therefore cannot be compared to others numbers as a number not can they be in that form nor can they be used for calculations. Also note that even if you have used a number to do calculations, using .toFixed() will convert that number to a string.
For example - you will need to use parseInt or parseFloat which will return a number:
var tipPercent = parseInt(document.getElementById(tipPercent).value);
It is not updating because you need to declare the input before the script. So the simple fix for this would be to move the entire <script> tag to below the last occurrence of <input>.
You can emulate the result using the W3Schools Tryit Editor and pasting a snippet of your code:
<!DOCTYPE html>
<html>
<body>
The content of the body element is displayed in your browser.
<input type="text" id="tipAmount" />
<script>
document.getElementById('tipAmount').value = 5*5;
document.getElementById('tipAmount2').value = 5*5;
</script>
<input type="text" id="tipAmount2" />
</body>
</html>
Notice how the code only updates tipAmount and not tipAmount2.

Javascript: why am i getting NaN even after using parseInt() function?

I want to create a HTML page that can do the following tasks:
Take a number from the user
Calculate a multiplication table and show it below the calculate button
Format of multiplication table should be like this, but on the same page and below the calculate button:
5
10
15
20
25
30
35
40
45
50
But I am getting NaN error, and also need help with how to get table displayed like this on the same page, please help and bear with my newbie mistakes :-)
<!doctype html>
<html>
<head>
<title>Multiplication Table</title>
<script type="text/javascript">
function createTable(nn)
{
for(i=1; i<=10; i++)
{
document.getElementById("t1").innerHTML = nn*i;
}
return true;
}
</script>
</head>
<body>
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" name="num" size=10></center><br />
<center><button type="button" onclick="createTable('n')">Calculate</button></center>
</form>
<center><p id="t1"></p></center>
<script type="text/javascript">
m = "num".value;
n = Number(m);
</script>
</body>
</html>
There's no mystery
m = "num".value;
here, m = undefined, because the string "num" has no property called value, i.e. it's undefined
n = Number(m);
Number(undefined) === NaN - because undefined is not a number
edit: also your onclick is called like this - createTable('n')
same problem, 'n' is not a number, it's a string .. 'n' * anything == NaN
There some problem with your program just see this one
<!doctype html>
<html>
<head>
<title>Multiplication Table</title>
<script type="text/javascript">
function createTable()
{
var nn = document.getElementById("num").value;
var str="<table>";
for(i=1; i<=10; i++)
{
str+="<tr><td>" + nn + "*" + i +" = " + (nn*i) + "</td></tr>";
}
str+="</table>";
document.getElementById("t1").innerHTML = str;
}
</script>
</head>
<body>
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" id="num" name="num" size=10></center><br />
<center><button type="button" onclick="createTable()">Calculate</button></center>
</form>
<center><p id="t1"></p></center>
</body>
</html>
You are converting a value to a number, but it's at the wrong time, and it's the wrong value. Then you don't even use the result.
This code:
m = "num".value;
n = Number(m);
is executed when the page loads, so that's before the user has had any chance to enter any number. It doesn't use the field where the user could enter a number, it only uses the string "num". As the string isn't the input element, it doesn't have a property named value, so m gets the value undefined. Turning that into a number gives you NaN, but that's not even the NaN that you get in the output, because the value of n is never used.
This code:
onclick="createTable('n')"
doesn't use the variable n, it uses the string 'n'. That is what gives you the NaN in the output, because that is what you get when you try to use the string in the multiplication. I.e. 'n' * i results in NaN.
To get the value that the user entered, you should get it at the time that the user clicks the button. Put the code in a function so that you can call it at that time. Use the getElementsByName method to locate the element:
function getValue() {
var m = document.getElementsByName("num")[0].value;
return Number(m);
}
When the user clicks the button, call the function to get the value and send it to the function that creates the table:
onclick="createTable(getValue())"
In your code where you create the table, you should put the items together and then put them in the page. If you put each item in the element, they will replace each other and you end up with only the last one. Also, you would want to put an element around each item, otherwise you end up with just a string of digits:
function createTable(nn) {
var str = '';
for(var i = 1; i <= 10; i++) {
str += '<div>' + (nn * i) + '</div>';
}
document.getElementById("t1").innerHTML = str;
}
Demo:
function createTable(nn) {
var str = '';
for(var i = 1; i <= 10; i++) {
str += '<div>' + (nn * i) + '</div>';
}
document.getElementById("t1").innerHTML = str;
}
function getValue() {
var m = document.getElementsByName("num")[0].value;
return Number(m);
}
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" name="num" size=10></center><br />
<center><button type="button" onclick="createTable(getValue())">Calculate</button></center>
</form>
<center><p id="t1"></p></center>

Categories