Reputation: 145
I'm new to js and my first and simplest function is not working with no errors
Other js codes work fine but not this
Here is the code: I'm expecting it to simply print what i write in the input field
HTML file:
<html>
<head></head>
<body>
<input type="text" id="myid">
<button onclick="myfunc()">click</button>
<script src="javascript.js"></script>
</body>
</html>
javascript.js file:
/*global document */
function myfunc() {
"use strict";
document.getElementById("myid").value;
}
Upvotes: 0
Views: 1268
Reputation: 1362
If you want to print the value of the input field, you can use console.log()
to print it's contents to the console. Save the value of the input in a variable for example. Then you can log the value of this variable in your browser's console, or use it for another purpose.
function myfunc() {
"use strict";
var value = document.getElementById("myid").value;
console.log(value)
}
document.getElementById("myid").value
did only get the input's value. But you didn't do anything with it.
You can also directly log the value without saving it to a variable first, see the example below.
function myfunc() {
"use strict";
console.log(document.getElementById("myid").value)
}
To show the value on the page, you can create a empty placeholder with an ID you can target. Then set the textContent
of this placeholder to the value of the input. See the example below.
function myfunc() {
"use strict";
var value = document.getElementById("myid").value;
/* Select the output placeholder */
var outputElement = document.getElementById("output");
/* Set the input fields value as the text content */
outputElement.textContent = value;
}
<html>
<head></head>
<body>
<input type="text" id="myid">
<button onclick="myfunc()">click</button>
<!-- This is the output placeholder -->
<p id="output"></p>
<script src="javascript.js"></script>
</body>
</html>
Upvotes: 2
Reputation: 230
If you want that to be visible in page, Create a div in HTML and set a id to it. After that in JS get the value in a variable
var myId=document.getElementById("myid").value;
and set that in new div id.
document.getElementById("printId").innerHTML="myId";
Upvotes: 1
Reputation: 436
It's a simple case of this function doesn't do anything.
Your code is correct in terms of getting the value of the input field with the id myid
.
But after that you're not doing anything with it, if you want to see it you do console.log()
on the value, or you can assign it to a variable to work with it later on const inputValue = document.getElementById("myid").value;
The line document.getElementById("myid").value;
simply just retrieves the value, and doesn't do anything with it, just throws it away, which is why you don't see any errors or feedback.
Upvotes: 1
Reputation: 169387
You don't do anything with the value, you just retrieve it and throw it away. Try
function myfunc() {
alert(document.getElementById("myid").value);
}
Upvotes: 1