简体   繁体   中英

Why will my function not return string inputted by user

I'm trying to have a user input a string or number on the page, hit submit and have console.log print the string just entered, however as much as I tried it will not print.

Am I missing something here? ( sorry for indentation)

<html>
<head>
<body>

 <form>
    <input id="userInput" type="text">
    <input type="submit" id = "submit()">
</form>

<script>
function submit() {
var test = document.getElementById("userInput");
 return console.log(test);
}
</script>
</body>
</head>
</html>

This code will give the result as you expect.you cannot return console.log in return function to get value and also dont use form so that it will always look for action in these kind of cases

 function submit() { var test = document.getElementById("userInput").value; console.log(test); return test; } 
 <div> <input id="userInput" type="text"> <button onclick = "submit()"> Submit</button> </div> 

You're doing a few things wrong. Just read the below code, I left explaining comments for you.

<html>
<head>
<body>
<form>
  <input id="userInput" type="text">
  <button type="button" id="submitBtn" onclick="submit()">Submit</button> // ID - can't be used for submitting a function
</form>      
<script>
function submit() {
  var test = document.getElementById("userInput");
  alert(test.value); // console.log() - is like a void function and it can't be returned
}
</script>
</body>
</head>
</html>

If you look in the console you'll see it's logging a reference to the element , not the value entered in it.

This is because your variable test stores a reference to the element.

var test = document.getElementById("userInput");

You need

var test = document.getElementById("userInput").value;

use Onclick attribute for Submit button! and Also the type of input should be button to prevent the refreshing.

<form>
  <input id="userInput" type="text">
  <input type="button" onclick= "submit()">
</form>

in JavaScript Code add the value property.

var test = document.getElementById("userInput").value;

Please check the below code. I think this is what you want. The problem was hooking up the event

<form>
    <input id="userInput" type="text">
    <input id="myBtn" type="submit">
</form>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
 var test = document.getElementById("userInput");
 console.log(test);
 return false;
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM