Button function calling another function - javascript

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>

Related

Javascript: insert input number value into closest number variable array onchange

I need to insert a user input number value into the "41" var value=getClosestNum(41,intarray);.
I know "41" needs to be calling the name or the id from the input but my rusty Javascript attempts always seem to result with = 1. I've tried several getDocument, getID variants, sub functions, etc without success.
Ideally, the result would be instantaneous by using onChange on the input field without page reload.
Yes, it has to be JavaScript for incorporation later.
<html>
<head>
<title>Find nearest value in javascript</title>
<script language="javascript">
// big array to come, example numbers
var intarray=[1,2,3,5,7,9,11,33,40,42,44,55,66,77,88];
// Now this function used to find out the close value in array for given number
function getClosestNum(num, ar)
{
var i = 0, closest, closestDiff, currentDiff;
if(ar.length)
{
closest = ar[0];
for(i;i<ar.length;i++)
{
closestDiff = Math.abs(num - closest);
currentDiff = Math.abs(num - ar[i]);
if(currentDiff < closestDiff)
{
closest = ar[i];
}
closestDiff = null;
currentDiff = null;
}
//returns first element that is closest to number
return closest;
}
//no length
return false;
}
</script>
</head>
<body>
<form>
<input type="number" id="test" name="test" onChange="?">
</form>
<script language="javascript">
document.write("Array: "+intarray+"<br>");
document.write("Value to find 41 <br>");
// CODE TO CHANGE "41" to id or named input
// 41 to reference input field
var value=getClosestNum(41,intarray);
document.write("Response Received "+value);
</script>
</body>
</html>
As I understand it, you are trying to use the input element to take a number, and you would like to return the closest number to that input from the array.
I registered a function that fires on an 'input' event. Try this:
HTML
Add the following element to see the output of the function. You can redirect it later to wherever you need it.
<p id="output"></p>
JavaScript
// wrap in an onload function to ensure
// that the elements exist before searching for them
window.onload = () => {
// cache of elements on the page you want to use
const testInputElement = document.getElementById('test');
const outputElement = document.getElementById('output');
// create a function that will fire whenever input is received
testInputElement.addEventListener('input', (event) => {
outputElement.innerHTML = getClosestNum(event.target.value, intarray);
})
};
onInput vs addEventListener('input')
Adding onInput directly to the HTML inside an element is not as secure as registering a function programmatically via addEventListener(). If you have a function called, say, handleInput(), simply pass that name to addEventListener as an argument like so
addEventListener('input', handleInput);
Your code with the changes
<html>
<head>
<title>Find nearest value in javascript</title>
<script language="javascript">
// big array to come, example numbers
var intarray=[1,2,3,5,7,9,11,33,40,42,44,55,66,77,88];
// Now this function used to find out the close value in array for given number
function getClosestNum(num, ar)
{
var i = 0, closest, closestDiff, currentDiff;
if(ar.length)
{
closest = ar[0];
for(i;i<ar.length;i++)
{
closestDiff = Math.abs(num - closest);
currentDiff = Math.abs(num - ar[i]);
if(currentDiff < closestDiff)
{
closest = ar[i];
}
closestDiff = null;
currentDiff = null;
}
//returns first element that is closest to number
return closest;
}
//no length
return false;
}
</script>
</head>
<body>
<form>
<input type="number" id="test" name="test" onChange="?">
</form>
<p id="output"></p>
<script language="javascript">
document.write("Array: "+intarray+"<br>");
document.write("Value to find 41 <br>");
// CODE TO CHANGE "41" to id or named input
// 41 to reference input field
var value=getClosestNum(41,intarray);
document.write("Response Received "+value);
// wrap in an onload function to ensure that the elements exist before searching for them
window.onload = () => {
// cache of elements on the page you want to use
const testInputElement = document.getElementById('test');
const outputElement = document.getElementById('output');
// create a function that will fire whenever input is received
testInputElement.addEventListener('input', (event) => {
outputElement.innerHTML = getClosestNum(event.target.value, intarray);
})
};
</script>
</body>
</html>
You're getting rid of your reference to the closestDiff on every loop, you need to keep that value throughout the loop and update it when the diff decreases.
function getClosestNum(num, arr) {
var closest;
if (arr.length > 0) {
closest = arr[0];
var diff = Math.abs(arr[0] - num);
for (var i = 1; i < arr.length; i++) {
var currentDiff = Math.abs(arr[i] - num);
if (diff > currentDiff) {
closest = arr[i];
diff = currentDiff;
}
}
}
return closest;
}

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;
};

A function that is not a function?

I'm still new to coding and I'm trying to make a cookie clicker type game. I get
upgradecursor is not a function
when I run it on Chrome. I don't really understand the problem as I have a function called upgradecursor.
Pls help! :(
<!DOCTYPE html>
<html>
<head>
<title> Test </title>
<script>
//List of variables
var cookie = 0;
var cursor = 1;
var cursorupgradecost = 10;
function addcookie(){
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
cookie = cookie + cursor;
// Add one
currentValue = currentValue + cursor;
// Put it back with the new +1'd value
textField.value = currentValue;}
function upgradecursor(){
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
cookie = cookie - cursorupgradecost;
// Minus one
currentValue = currentValue - cursorupgradecost;
// Put it back with the new -10'd value
textField.value = currentValue;
//change the cost of the upgrade
cursorupgradecost = cursorupgradecost * 1.5;
//Upgrade the cursor
cursor = cursor + 1;
}
</script>
</head>
<body>
<script>
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
</script>
<button type ="button" onClick = "upgradecursor()"/>Upgrade Cursor </button>
<input type="text" value="0" disabled name="lvl">
<br>
<button type="button" onClick="addcookie()"/>Add Cookie</button>
<input type="button" value="Cookies" disabled name="clicker">
<input type="text" value="0" id="textField" readonly/>
</body>
</html>
You are overwriting upgradecursor with a global variable after you include the JavaScript.
<script>
if (cursorupgradecost > cookie) {
upgradecursor = false;
} else {
upgradecursor = true;
}
</script>
This is the offending code. You need to rename this variable to something else to avoid overwriting the function.
Additionally, you should definitely avoid declaring global variables like this and look at making your code more encapsulated/modular.
--
Update based on your objective: If you want to only upgrade the cursor given a certain use case, then it might be useful to have a specific click handler that will run this check inside itself before calling upgradecursor. For example: -
function onCursorClick() {
if (cursorCost > cookie) {
// do something
} else {
upgradeCursor();
}
}
Notice how I have used camel casing to declare my functions and variables? Make sure you update your variable declarations to match my casing. This is common practice. You can read more on coding conventions here: W3Schools JavaScript Style Guide
I'd like to point out listeners should be attached via JavaScript (see DOM Event Listeners), but make sure you update the click handler to match our update, like so: -
<button type="button" onClick="onCursorClick()"/>Upgrade Cursor</button>
You have this:
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
So while you started out by defining upgradecursor as a function, you overwrote it with a boolean before you ever called it.
The problem is here:
<script>
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
</script>
What on earth is that supposed to even do?
Remove it and it should work.

nothing happens when I click button

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;

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