This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 8 years ago.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
user name:
<input type="text" id="t1">
<br>
<button type="button" onClick="myFunction()">display</button>
<script type="text/javascript">
function myFunction() {
var str;
str = document.getElementById("t1");
alert(str);
}
</script>
</body>
</html>
In the above program it is displaying [object] inside the alert box,I don't know why,I want to display what ever user input in the text box.help me..........
You're only getting the html element which is represented as an object, not the actual contents of the <input>. You need to explicitly get that content using .value:
function myFunction() {
var str;
str = document.getElementById("t1").value;
alert(str);
}
Change:
str = document.getElementById("t1")
to:
str = document.getElementById("t1").value;
jsFiddle example
document.getElementById("t1") refers to the element so you need to specify the property of the element you want. In this case, the value.
Your str variable contains a reference to the object itself, not the text inside. What you want is:
str = document.getElementById('t1').value;
You should use t1.value in the alert. t1 is the whole input element but you are only interested at what has been entered i.e. its value.
rather than alert(str), use console.log(str), then check browsers console
Related
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>
StackOverflow,
I'm a NOOB learning slowly. I got some errors when trying to validate the following code in HTML 5 validator and don't know where the errors are:
<!DoctypeHTML>
<HTML>
<head>
<title> Javascript Programming!</title>
<script type = “text/javascript”>
<function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
If (myValue ==0) {
alert(‘please enter a real value in the box’);
Return;
}
Var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</head>
<body>
</body>
</html>
Errors: Error: Bad value “text/javascript” for attribute type on element script: Expected a token character but saw “ instead.
From line 5, column 2; to line 5, column 34
↩ ↩
Error: End of file seen when expecting text or an end tag.
At line 18, column 7
dy>↩
Error: Unclosed element script.
From line 5, column 2; to line 5, column 34
↩ ↩
Any feedback? Thanks guys and gals.
PreYvin
You are using typographical quotes - change these to regular quotes. (single and double)
Ok, you've got a whole lot of invalid code (HTML and JavaScript) here:
<!DoctypeHTML>
Should be (case doesn't matter):
<!DOCTYPE html>
This:
<script type = “text/javascript”>
contains typographically formatted quotes instead of non-formatted quotes, which is a problem, but you don't even need the type=text/javascript anyway, so you can just write:
<script>
function is not an HTML tag, so this:
<function substitute () {
should be:
function substitute() {
Next, you are using formatted quotes in your JavaScript:
var MyValue = document.getElementID (‘mytextbox’).value;
which should be unformatted, like this:
var MyValue = document.getElementID ('mytextbox').value;
HTML isn't case-sensitive, but JavaScript is, so this:
If (myValue ==0) {
needs to be this:
if (myValue == 0)
More quote problems here:
alert(‘please enter a real value in the box’);
Should be:
alert('please enter a real value in the box');
More case-sensitivity issues here:
Return;
Should be:
return;
More quote and case-sensitivity issues here:
Var myTitle = document.getElementbyID (‘title’)
Should be:
var myTitle = document.getElementbyID ('title');
Lastly, when your script is finished and it's time to return to HTML, you didn't close your script, so this:
}
</head>
Should be:
}
</script>
</head>
You can always validate your HTML at: http://validator.w3.org
And, you can validate your JavaScript at: http://www.jslint.com
You also have invalid JavaScript so this should be valid.
<!doctype html>
<HTML>
<head>
<title> Javascript Programming!</title>
<script>
function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
if (myValue ==0) {
alert(‘please enter a real value in the box’);
return;
}
var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
</body>
</html>
you have an extra < in your code. but you need to revisit your javascript as it has many problems the script tag is not closed.
<!DoctypeHTML>
<HTML>
<head>
<title> Javascript Programming!</title>
<script type = “text/javascript”>
function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
If (myValue ==0) {
alert(‘please enter a real value in the box’);
Return;
}
Var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
</body>
</html>
Lots of basic syntax errors here.
<!DoctypeHTML> should be <!DOCTYPE html>
the first error you listed, (Bad value “text/javascript” for attribute type on element script: Expected a token character but saw “ instead.) is due to a funky double quote character: “ It should be " This probably originated from your text editor. What are you using? I like Sublime, but there are lots of options. The important thing is that you use a text editor designed for coding.
the next two errors are due to your script tag not being closed. Just add </script> at the end of the script.
Like I said, these are just simple syntax errors though. What you really need to learn here is how to look at those error messages and tell what's going on. Notice how the error messages reference a line number and column number? That's to tell you where the problem is. (Sometimes it can be off depending on the error, but worry about that later). Take a look at the line it's complaining about, read the error message, and you should be able to figure out what's wrong.
Close your <script> tag.
Remove < from <function
Use regular quotes instead of typographical
space between Doctype and html ie. <!doctype html>
Lastly, keywords should be all smallcase ie. if, return, var
Updated
<!doctype html>
<html>
<head>
<title> Javascript Programming!</title>
<script type = 'text/javascript'>
function substitute () {
var MyValue = document.getElementID ('mytextbox').value;
if (myValue == 0) {
alert('please enter a real value in the box');
return;
}
var myTitle = document.getElementbyID ('title')
myTitle.innerHTML = myValue;
}
</script>
</head>
<body></body>
</html>
This question already has answers here:
How do I replace a bit of text with string variable in javascript?
(2 answers)
Closed 7 years ago.
On click I'm getting text in HTML. I have a variable in Javascript called content I want to get the text input and change a part of the Javascript variable.
HTML CODE:
<html>
<head>
<link href="latent.css" rel="stylesheet">
</head>
<body>
<button onclick="makePage()">Generate Link</button>
Image link: <input type="text" name="img" id = "img"><br>
Content: <input type="text" name="content" id = "content"><br>
<script src="makePage.js">
</script>
<script>
var img = document.getElementById("img").value;
var content = document.getElementById("content").value;
</script>
</script>
</body>
</html>
JAVASCRIPT CODE:
function makePage(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = '<html><head><meta name="something:something" content=""></head><body></body></html>';
xmlhttp.open("GET","http://ahansabharwal.com/makePage.php?content=" + content, true);
xmlhttp.send();
}
In the variable called content I want to replace the image link in the content of the twitter:image
meta name="twitter:image" content="http://graphics8.nytimes.com/images/2012/02/19/us/19whitney-span/19whitney-span-articleLarge.jpg"
AND
I would like to replace the content of the meta name="twitter:description" content="NEWARK - The guest list and parad[....]
with the content inputted by the user.
I solved it by using replace();
What I did was:
var contentJS = document.getElementById('contentInput').value;
var contentNew = content.replace("info", contentJS);
I replaced the context to just info. Now it stores the value of the user input, then searches for the value of 'info' in the string. When it finds it, it simply gets replaced with the user input (contentJS)
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;
This question already has answers here:
Changing the way a JavaScript Alert() or Prompt() looks
(4 answers)
Closed 8 years ago.
How can I use html tag in this javascript?
First of all, why <br> doesn't work in prompt. Secondly, why can't I use tags for this code (poundOne.pound) to make the font larger by using css or html code such as <h1>, <h2>, <h3>... or <div style="......">?
<html>
<head>
<script type="text/javascript">
function poundToKgConvertor( pound ){
this.pound = pound;
this.convertorDon = convertor;
}
function convertor(){
var convert = this.pound * 0.453592;
return convert;
}
var poundOne = new poundToKgConvertor(prompt ("Convert Pound to Kilogram!<br> Please insert your number of pound!"));
</script>
</head>
<body>
<script type="text/javascript">
document.write(poundOne.pound + " Pound = " + poundOne.convertorDon() + " <b>Kilogram</b>");
</script>
</body>
</html>
You can't use HTML in prompt/alert dialogs. However you can use new line characters:
prompt ("Convert Pound to Kilogram!\n Please insert your number of pound!");