In the following codepen I am trying to get text from input field. I am then trying to creat an object from that data. I get undefined for the userData even though I am returning it in my event listener.
class Name {
constructor(name) {
this.name = name;
}
}
const getUserData = (function() {
let userInput = document.getElementById('name').value;
return { name: userInput};
})();
document.getElementById("btn").addEventListener("click", function (event) {
event.preventDefault();
const userData = getUserData();
});
console.log(userData);
const nameObj = new Name(userData);
console.log(nameObj);
class Name { constructor(name) { this.name = name; } } const getUserData = function() { let userInput = document.getElementById('name').value; return { name: userInput}; }; document.getElementById("btn").addEventListener("click", function (event) { event.preventDefault(); const userData = getUserData(); console.log(userData); const nameObj = new Name(userData); console.log(nameObj); });
#btn { height: 30px; width: 100px; background-color: blue; color: white; text-align: center; display: flex; justify-content: center; align-items: center; margin-top: 5px; }.form-container { padding: 10px; }
<form id="test-form"> <div class="form-container"> <input id="name" type="name" name="name" placeholder="type your name here"> <div id="btn">Click Me</div> </div> </form>
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.