I need to read the user's name from a “Form” text input and display it somewhere on the page in a greeting message i.e. Hello (user). I need to use the “Form” input and extract the user’s name from the URL using the query string. I also need to read the query string when the page is loaded, not when the button is pressed i.e. need to write a function for the onload
event
This all must be done in one HTML file not two separate HTML files.
Any help will be appreciated!
<form>
<input type="text" name="user_name" placeholder="Enter your name!">
<button type="submit">Apply!</button>
</form>
CodePudding user response:
You can do this by adding a 'keyup' event listener. See code snippet below for an example.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id="h1">Hello World</h1>
<form>
<input type="text" name="user_name" placeholder="Enter your name!" id="input">
<button type="submit">Apply!</button>
</form>
<script>
// update the body h1 element with real-time user input
function updateH1() {
var h1 = document.getElementById("h1");
var input = document.getElementById("input");
h1.innerHTML = input.value;
}
// call updateH1() when the user types in the input element
function init() {
var input = document.getElementById("input");
input.addEventListener("keyup", updateH1);
}
// call init() when the page loads
window.addEventListener("load", init);
</script>
</body>
</html>
CodePudding user response:
// use the ids to access the elements in the DOM
const userName = document.getElementById("user-name");
const output = document.getElementById("output");
// if there query string is not empty
if (location.search !== '') {
// get the parameters
const params = new URLSearchParams(location.search);
// pick out the user name
const un = params.get("user_name");
// update the input and the display
output.textContent = userName.value = un;
}
<form>
<input type="text" id="user-name" name="user_name" placeholder="Enter your name!">
<button type="submit">Apply!</button>
</form>
<p>Hello <output id="output"></output></p>