Now this is just for reference for a future project but I am trying to call a function that reads in a string but displays a float after. So I first check the string then display a random number. The problem I am having, I think, is with the document.getElementById part. Any suggestions??
HTML File:
<html>
<body>
<input type="text" id="letter" value=""/><br/>
<input type="button" value="LETS DO THIS!" onclick="floatNum();"/></br>
<script type="text/javascript" src="letNum.js"></script>
</body>
</html>
External JS File:
function floatNum()
{
var val1 = document.getElementById("letter");
if (isNaN(val1)
{
alert(Math.random())
}
}
the following code is working:-
in your code,you missed closing parenthesis ")" near to "if condition"
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>demo</title>
<script type="text/javascript">
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value))// using input fields value not the whole object
{
alert(Math.random());
}
}
</script>
</head>
<body>
<input type="text" id="letter" value="" /><br />
<input type="button" value="LETS DO THIS!" onclick="floatNum();" />
</body>
</html>
Yes, you want to pass in the element in the function, like so:
<input type="button" value="LETS DO THIS!" onclick="floatNum(document.getElementById('letter'))"/></br>
And in your JS
function floatNum(el)
{
if (isNaN(el)
{
alert(Math.random())
}
}
In case of a reusable function - try not to make it dependent on your DOM. Think about what would happen if you rename your element or want to use this function again. You couldn't before - now you can.
The problem is on this line:
var val1 = document.getElementById("letter");
It should be:
var val1 = document.getElementById("letter").value;
The first sets val1 to the DOM element representing the input tag, the second sets it to the text value of the input tag (its contents).
You need to process the value of input field not the input field itself.
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value) // using input fields value not the whole object
{
alert(Math.random())
}
}
You don't grab the value of the input, but the input itself.
Correct code would be :
var val1 = document.getElementById("letter").value;
Related
var data = document.getElementById('myFieldId');
console.log(data.value);
<!DOCTYPE html>
<html>
<head> </head>
<body>
<input type="text" id="myFieldId"/>
<script src="main.js"></script>
</body>
</html>
I expect when I write any text in the input, it would print the corresponding text. But I don't get anything in the console. What should I do?
You need to add an event listener that executes as soon as someone inputs text.
There is no such thing as binding a variable to a text input; this needs to be implemented by yourself.
See this example:
const data = document.getElementById('myFieldId');
data.addEventListener(
'input', // first argument is the name of the event you want to react to
// second argument is the function that should execute when the event occurs
function(inputEvent) {
console.log(data.value);
}
);
<input type="text" id="myFieldId"/>
You code start at load page so is empty, i add an onchange event so when you finish to write console.log will output the value.
var data = document.getElementById('myFieldId');
data.onchange = function()
{
console.log(this.value);
};
<!DOCTYPE html>
<html>
<head> </head>
<body>
<input type="text" id="myFieldId"/>
<script src="main.js"></script>
</body>
</html>
I'm trying to get it to add the two numbers inputted by the user, and print it inside of the p tag. Any help would be much appreciated. Here's the code:
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var p=p1.innerHTML;
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer() {
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=num1.innerHTML;
var y=num2.innerHTML;
p=x+y; //print the sum of the two values, inside of the p tag
}
</script>
</body>
To decode what's going on in your JavaScript, please see my annotations to the code:
var p1=document.getElementById("p"); // Stores a reference to an element with id "p" to variable p1
var p=p1.innerHTML; // Retrieves the HTML contents of said attribute and assigns it to variable p (not needed)
var calc=document.getElementById("calculate"); // Stores a reference to an element with id "calc" (your button) to variable calc
calc.addEventListener("click", answer); // Attaches an event handler to the element referenced via variable calc
function answer()
{
var num1=document.getElementById("num1"); // Stores a reference to an element with id "num1" in variable num1
var num2=document.getElementById("num2"); // Stores a reference to an element with id "num2" in variable num2
var x=num1.innerHTML; // Retrieves the HTML contents of the element referenced by num1 and stores it in variable x (error)
var y=num2.innerHTML; // Retrieves the HTML contents of the element referenced by num2 and stores it in variable y (error)
p=x+y; // Since both x and y are strings, they are concatenated and the result is stored in variable p (produces wrong result)
// Missing assignment of result to output element
}
The problem: You don't have a statement that actually assigns the result to the paragraph marked with ID "p", instead you are modifying a variable.
Furthermore, since you are retrieving strings from the input fields, the addition is in reality a concatenation, producing a false result (num1.value and num2.value are needed to access the actual values). I'd also suggest converting things to an integer - parseInt does the trick here.
There are several errors in your code, will try to address them one by one:
The <button> by default is type="submit" which when pressed refreshes the whole page, not the intended behaviour. To fix it just need to add type="button", which makes it behabe like a button that by itself does nothing.
The result of p=x+y, you are doing nothing with it. p is just a variable containing the result of the operation, but you need then to insert it inside the <p> tag for it to show up. Adding this at the end of your answer() function should fix it: p1.innerHTML = p;.
The <input> values, those are stored in the value property instead of the innerHTML. So it should look like this var x=num1.value; and var y=num2.value;.
The "sum", in JavaScript the + operator can be used both to add numerical values and to concatenate strings, and the engine chooses what to do guessing by the type of the values you are using, in your case strings. Because even if you type 1 in the input, retrieving it later with .values will return it as a string. You have to cast it back to a number to get the desired result. Just doing this is enought var x=Number(num1.value); and var y=Number(num2.value);.
And that's all.
Here you have your code with the fixes applied.
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button type="button" id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var p=p1.innerHTML;
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer() {
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=Number(num1.value);
var y=Number(num2.value);
p=x+y; //print the sum of the two values, inside of the p tag
p1.innerHTML = p;
}
</script>
</body>
Sorry for the lengthy answer but tried to attack each error by itself and it's explanation as clear and simple as I can do.
p = p1.innerHTML
copies the contents of your paragraph into the variable p.
So your
p = x+y
merely assigns a new value to your variable p and doesn't change the innerHTML of your paragraph.
Try
p1.innerHTML = (x + y) + ''; // + '' converts the result of x + y to a string
You should also use '.value' instead of '.innerHTML' to get the contents of your inputs and then convert them to numbers with parseInt() before adding them.
There were quite a few issues; you can't copy the innerHTML of a p and then assign it a value. You must convert the input values to integers in order to add them. With inputs you can ask for their "value" rather than innerHTML.
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer(e) {
e.preventDefault();
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=parseInt(num1.value, 10);
var y=parseInt(num2.value, 10);
p1.innerHTML = x+y; //print the sum of the two values, inside of the p tag
}
</script>
</body>
</html>
I need your help,
Normally when a user inputs data, how can the code be modified below so as to program it to ignore any whitespacing, i.e. "a blank keyboard space" ?
Here is the HTML markup in question:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
$("#fileno").bind("input", function(e) {
$('#save').prop('disabled', false)
});
}
</script>
</head>
<body>
<input type="button" value="save" id="save" disabled>
</body>
</html>
Use the Trim function
https://www.w3schools.com/jsref/jsref_trim_string.asp
fieldName = element.property.Trim()
You can try adding a pattern attribute with regex to check or you can add a simple check in javascript when clicking the button to submit it.
regex pattern like:
pattern="[A-Za-z0-9]"
javascript jquery check like:
if($('#inputId').text()) this check will not pass if the value is undefined, null or empty string
hi so i am new to javascript and i am trying to make a simple calculator using HTML and js. However i have run into a problem where i press the button to calculate the answer and it wont do anything. I tried it in an online ide and it just gave me the wrong answer. here is the code can anyone help. thanks--
<!DOCTYPE html>
<html>
<head>
<title>calculator</title>
<script type="text/javascript">
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_1').value);
document.getElementById('answer').innerHTML = answer;
};
</script>
</head>
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<input type="submit" name="equals" id = "equals" value="=">
<p id = "answer"></p>
</body>
</html>
forms including onClick conditions without GET/POST methods , generally use button .
<input type="button" name="equals" id="equals" value="=">
I guess you are adding same variables twice ?
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_2').value);
You're adding the value from the same input twice and you have to set the event handler after the button is created, .
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<input type="submit" name="equals" id = "equals" value="=">
<p id = "answer"></p>
<script type="text/javascript">
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_1').value);
document.getElementById('answer').innerHTML = answer;
};
</script>
</body>
The main problem is you are adding the event click to element equals, but in these moment, element equals doesn't exists.
wrap your document.getElementById into window.onload function to say javascript: "when all the document finish to load, add the event click to element equals"
try this:
window.onload = function () {
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value, 10)+ parseInt(document.getElementById('number_2').value, 10);
document.getElementById('answer').innerHTML = answer;
};
}
Another important thing I have added ,10 to your parseint, this is to make sure that the conversion is to a number into decimal mode
"The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)"
Source: parseInt use
i fixed it now i had to wrap my code in a window.onload
<!DOCTYPE html>
<html>
<head>
<title>calculator</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_2').value);
document.getElementById('answer').innerHTML = answer;
};
};
</script>
</head>
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<button id = "equals">=</button>
<p id = "answer"></p>
</body>
</html>
This is the code I used. It takes the first name and the surname from the user and then uses them in the MyChecker function where it matches up the names used to create different alerts. I can't get the MyChecker function to link to the values inputted by the user?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Question 1</title>
</head>
<body>
<p>What's your name?</p>
<form action="action.php"> //This form gets the input from the user
First Name
<br><input type="text" name="FirstName" value="" id="txt1"><br>
Second Name
<br><input type="text" name="SecondName" value="" id="txt2"><br>
<button onclick="myFunction()">Submit</button>
</form>
<script type="text/javascript">
function myFunction() { //This function gets the values inputted by the user
document.getElementById('txt1').value);
document.getElementById('txt2').value);
}
var x= FirstName.localeCompare("Donald");
var y= SecondName.localeCompare("Trump");
MyChecker();
function MyChecker()
{
if(x==0&&y==0)
{
alert("I love the poorly educated");
}
var a= FirstName.localeCompare("Edward");
var b= SecondName.localeCompare("Snowden");
if(a==0 && b==0)
{
var ask=prompt("Would you mind collecting your cake from our office in Pennsylvania?","Choose between yes or no");
var cmp=ask.localeCompare("yes");
if(cmp==0)
{
alert("We'll even reimburse your plane tickets!");
}
else
{
alert("Perhaps next time...");
}
}
if(a!=0 && b !=0 && x !=0 && y!=0)
{
alert("Carry on...");
}
}
</script>
</body>
</html>
I touched up your indentation and hopefully it helps to expose the issue. When you submit the form, you will call myFunction, which I've copied here for clarity:
function myFunction() { //This function gets the values inputted by the user
document.getElementById('txt1').value);
document.getElementById('txt2').value);
}
... and that's it. These values aren't even saved.
You probably mean to have myFunction call MyChecker, so that your logic will be executed each time the form is submitted.
You might also consider having MyChecker take in the FirstName and SecondName as parameters, since myFunction is already reading values from the form.