js math function returns nan - javascript

I am trying to write a couple of simple js functions and the first one (and the most simple one) doesn't seem to work. this one is my html page, I have no css.
FunctionLib.js is my file and other script imports jquery(it worked perfectly in my other project)
I just need to show the answer of the function squareSum after the button is clicked.
<!DOCTYPE html>
<html lang="en">
<!-- МЕТА-ІНФОРМАЦІЯ -->
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/FunctionLib.js"></script>
</head>
<body>
<div class="square-sum">
<form name="mathematics">
Enter х: <input type="number" id="x-square"> <br>
Enter y: <input type="number" id="y-square"> <br>
<button onclick="squareSumContainer()">OK</button>
</form>
<p>x^2+y^2 = <span id="square-answer"></span></p>
</div>
</body>
</html>
and my js file:
function squareSum(a, b) {
return a * a + b * b;
}
function squareSumContainer() {
var x = parseInt($('#x-square').html(), 10);
var y = parseInt($('#y-square').html(), 10);
$("#square-answer").html(squareSum(x, y));
//document.getElementById("square-answer").innerHTML = myFunction(4, 3);
var answer = squareSum(x, y);
//alert(answer);
}
And when I press the button nothing happened. I tried using alert to show the answer and it appeared to be NaN.
I am extremely new to js so I don't know what to do at all.

So as #Bravo and #freedomn-m said, the problem was in the part where I tried to use .html() on input instead of .val()

Related

Is the problem the onclick method or the represenation of the html element as a object

I'm new to javascript and this has been driving me nuts for the last hour
Here's the html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Number Guessing Game</title>
<link rel="stylesheet" href="styles/main.css">
</head>
<body>
<h1>Number Guessing Game</h1>
<p>Greetings hominid. I've selected a number between 1 and 100. See if you can guess it in 10 turns or fewer. I'll tell you if your guess was too high or too low.</p>
<label for="guess">Enter your guess:</label>
<input id="guess">
<button id ="submit">Submit</button>
<p id="response"></p>
<p id="guess-count"></p>
<p id="previous-guesses"></p>
<script src = scripts/game.js ></script>
</body>
</html>
And here's the javascript
const submitButton= document.getElementById('submit')
alert('hi')
submitButton.onClick = function submitGuess() {
alert('button is live')
}
For some reason the submitGuess function is not being executed at all (at least I'm not seeing the alert). I had a lot more javascript but I reduced it to find out why it wasn't working.
Any help is much appreciated
As pointed out in the comments, you can add the event handler in the JavaScript via EventTarget.addEventListener, rather than the inline HTML attribute. For example:
document.querySelector('#submit').addEventListener('click', event => {
console.log(`${event.target.id} was clicked`)
});
<h1>Number Guessing Game</h1>
<p>Greetings hominid. I've selected a number between 1 and 100. See if you can guess it in 10 turns or fewer. I'll tell you if your guess was too high or too low.</p>
<label for="guess">Enter your guess:</label>
<input id="guess">
<button id="submit">Submit</button>
<p id="response"></p>
<p id="guess-count"></p>
<p id="previous-guesses"></p>
const submitButton = document.getElementById('submit')
this line get the value before the DOM fully loaded the solution is to define the const after the page load like this
window.onload = function(){
const submitButton = document.getElementById('submit')
alert('hi')
if(submitButton){
submitButton.addEventListener('click', function() {
alert("Clicked!");
});
}else{
alert("Something Wrong")
}
}

Javascript display innerHTML on the same page

So I am testing the permute function of D3.js and it works just fine.
The issue I am having is to display the results on the same page using innerHTML, it always reloads in order to display.
I am probably missing a detail here, can someone help?
permute.html:
<html>
<head>
<meta charset="UTF-8">
<script language="JavaScript">
function* permute(keys) {
var size = keys.length,
c = Array(size).fill(0),
i = 1;
yield keys;
while (i < size) {
if (c[i] < i) {
var k = i % 2 && c[i];
[keys[i], keys[k]] = [keys[k], keys[i]];
c[i]++;
i = 1;
yield keys;
} else {
c[i++] = 0;
}
}
}
function showPermutations(){
var input = document.getElementById("keys").value;
document.getElementById('results').innerHTML=input;
for (var words of permute(input.split(/\s+/))) {
document.write(words.join(''));
document.write("<br>");
}
}
</script>
<body>
<form>
<label><b>Keywords</b></label></br>
<input type="text" id="keys" name="keys"></br>
</form>
</br>
<input type="submit" value="Permute" onclick="showPermutations();"></br>
<p><span id='results'></span></p>
</head>
</body>
</html>
Some of you pointed out the issue is caused by the submit button, but in this other example, using submit, the JS works just fine on the same page:
test.html
<html>
<head lang="en">
<meta charset="UTF-8">
<script language="JavaScript">
function showInput() {
document.getElementById('display').innerHTML =
document.getElementById("user_input").value;
}
</script>
</head>
<body>
<form>
<label><b>Enter a Message</b></label>
<input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showInput();"><br/>
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>
When you click the submit button, the page will automatically reload. You should prevent that by calling the preventDefault method of the event object that is passed to the event handler, in your case, that handler would be showPermutations.
Make that function receive one argument, called e, ev, or event (as it is normally called) and inside it, execute the preventDefault method before anything else.
function showPermutations(e){
e.preventDefault();
...
}
Or don't use a submit button.

Global replace user input text to modified output by element ID in JS

I am currently learning to use the replace method in JS. I was able to get it to work in a simple function using the console to check the output. However I am now working on making a simple user interface to interact with the function and it has caused some difficulty. I can get the function to accept and re-print the user's text, but the replace portion doesn't seem to be functioning properly as I've written it. Here is the HTML:
<!DOCTYPE html>
<!-- Create a function grabText that replaces the char - with _ -->
<html lang="en">
<meta charset="utf-8">
<head>
<title>HMTL Template</title>
</head>
<body>
<input type="text" id="inputField"
placeholder="Input Text"/>
<button id="clickButton" onclick="grabText();">Run</button>
<p id="outputText"></p>
</body>
</html>
And here is the JS:
var inputText;
function grabText () {
inputText = document.querySelector("#inputField");
document.getElementById("outputText").innerHTML = inputText.value;
inputText.value.replace(/-/g , "_");
document.getElementById("outputText").innerHTML = inputText.value;
}
I suspect there is an issue with where and how I am using .value . Thanks for any help.
keep in mind replace returns a new string, it doesn't change the existing one.
var inputText;
function grabText() {
inputText = document.querySelector("#inputField");
document.getElementById("outputText").innerHTML = inputText.value.replace(/-/g, "_");
}
<input type="text" id="inputField" placeholder="Input Text" />
<button id="clickButton" onclick="grabText();">Run</button>
<p id="outputText"></p>

Getting input from a html textbox then putting it into a Javascript variable not working

This is my code. When I click the calculate button it is displaying just the number 35. WHere have I gone wrong and how can I fix it?
<!doctype html>
<html>
<head>
<title>JS Practise 2</title>
</head>
<body>
<h1> Problem 1.1 </h1>
<script language="javascript">
var topsoil_amount = 1;
function calculate() {
var topsoil_amount = document.getElementById(Input);
var topsoil_cost = 15;
var cost = (topsoil_amount * topsoil_cost) + 35;
alert(cost);
}
</script>
<br>
<input type="text" name="Input" size="16" id="Input">
<input type="button" value="Calculate" onClick="calculate()">
</body>
</html>
topsoil_amount is a DOM element, not a number. You need to reference the value. Secons issue is you need quotes around the id.
var topsoil_amount = document.getElementById("Input").value;

Why does this give "undefined" error?

I am trying to get the user to put something into the text area and the output should be what he wrote repeapiting x amount of times, but I get an error "document.forme is undefined".
Can you please help me understand why it is undefined?
My code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>input home work</title>
<script type="text/javascript">
var help= document.forme.tryout.value;
for (x=1; x<=10;x++){
function numberCheak (){
document.write("this is"+" "+help++);
}
}
</script>
</head>
<body>
<form name="forme">
<input name="tryout" type="text" />
<input type="button" value="click me" onClick="numberCheak();"/>
</form>
</body>
</html>
Ok, you have a few problems. The first is that you are trying to access a form element that doesn't exist yet: the script is above the form element, so the form doesn't exist when you try to get it. If you move the script to the bottom of the page it will work better.
Second, the loop should be inside the function, not wrapped around the function.
Third, document.write has weird side effects and causes the document to be rewritten and will stop the script from continuing correctly.
Here's my revised script
function numberCheak() {
var help = document.forme.tryout.value;
for (var x = 1; x <= 10; x++) {
document.getElementById("output").innerHTML += help;
}
}
and the HTML form that goes with it
<form name="forme" id="forme">
<input name="tryout" type="text" />
<input type="button" value="click me" onclick="numberCheak();" />
<span id="output"></span>
</form>
You can see it in action on jsFiddle.
Forms are stored in collection and can be accessed like this:
var form = document.forms[i];
or
var form = document.forms[name];
In your case, i is 0 and name is forme.

Categories

Resources