Home > Enterprise >  How to get input value and replace part of p-tag with the value using JS?
How to get input value and replace part of p-tag with the value using JS?

Time:03-23

I want the to get the input value and for it to replace a part of the P tag text.

Please see my code below:

<input  id="strangers-name" placeholder="Nickname" type="text" onblur="getStrangerName()"/>

<p id="welcome-stranger-note">Welcome, stranger</p>

<script>
    function getStrangerName() {
        const user = document.getElementById('strangers-name').value;
        document.write("Welcome, "   user);
    }
</script>

What I'm hoping to achieve is, if a user entered their nickname in the input, it will replace the default text inside the paragraph tag from "Welcome, stranger" to "Welcome, (insert user input)"

Right now, it's replacing the whole document instead of just the p tags.

Extra question (if possible): How do I store the user's input into the local storage so on their next visit, their name will still be there in the replaced paragraph text?

Thank you in advance! I'm just learning JS..

CodePudding user response:

  1. Write a function to set the text in the paragraph
  2. Get the value from localStorage and if it exists, set the text
  3. Add a change event listener to handle the user input that can set the paragraph text and save the value into local storage

// fake localStorage for snippet sandbox, just ignore
// and definitely don't include it in your code
const localStorage={getItem(...args){console.log("localStorage.getItem",...args)},setItem(...args){console.log("localStorage.setItem",...args)}}

// Storage key name
const STORAGE_KEY = "nickname";

// Grab a reference to the <p> element
const welcome = document.getElementById("welcome-stranger-note");

// Sets the text within the welcome element
const setNickname = (name) => {
  // See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
  welcome.textContent = `Welcome, ${name ?? "stranger"}`
}

// Add a "change" event listener
document.getElementById("strangers-name").addEventListener("change", e => {
  const nickname = e.target.value.trim();
  // Only set if not empty
  if (nickname) {
    setNickname(nickname);
    localStorage.setItem(STORAGE_KEY, nickname);
  }
});

// Call setNickname with value from localStorage
setNickname(localStorage.getItem(STORAGE_KEY));
<input id="strangers-name" placeholder="Nickname" />

<p id="welcome-stranger-note"></p>

  • Related