1

Does anybody have suggestions for allowing a input field to update parts of a paragraph?

example, the visitor would type in their name, and it would customize the paragraph to use their name.

<input type="text"> 
<button>Submit</button>

<<Name>> went for a run, then <<Name>> took a nap.
jprly
  • 23
  • 4

2 Answers2

2

I'm going to guess that you are new to the DOM (Document Object Model).

One approach would be:

  • include in your markup <spans> (identifiable by id or class or data-*) which will hold the submitted data
  • create a function which can populate the <spans>
  • invoke the function using an EventListener
  • attach the EventListener to the <button>

Then the <button>, when clicked, will trigger the EventListener which will invoke the function which will populate the <spans>.

Working Example:

// GET ELEMENTS FROM DOM
const nameInput = document.getElementsByName('nameInput')[0];
const submitButton = document.getElementsByClassName('submitButton')[0];
const nameSpans = document.querySelectorAll('[data-type="name"]');

// DECLARE FUNCTION
const populateNameSpans = () => {

  nameSpans.forEach((nameSpan) => {
  
    nameSpan.textContent = nameInput.value;

  });

}

// ATTACH EVENT LISTENER TO submitButton
submitButton.addEventListener('click', populateNameSpans, false);
<input name="nameInput" type="text" /> 
<button type="button" class="submitButton">Submit</button>

<p><span data-type="name"></span> went for a run, then <span data-type="name"></span> took a nap.</p>
Rounin
  • 27,134
  • 9
  • 83
  • 108
  • So if I was working this into a wordpress site, I would use the above code in the functions.php file, and the html on the page? just wrap it in function brackets? function replaceName() { //code goes here } – jprly Dec 05 '19 at 16:43
  • PHP is a server-side scripting language. The code above is javascript which is used most often as a client-side scripting language (ie. a scripting language which runs in the browser, rather than on a remote server). – Rounin Dec 05 '19 at 19:36
0

This simple demo here will place whatever is typed in the input inside the placeholder elements within the <p> paragraph (I've used here <mark> elements for the sake of the demo).

As you can see, the "trick" is to place HTML tags (DOM elements) at the places where you wish to "inject" text into, and then find those elements using querySelectorAll and iterate them and set their innerHTML when wanting to set their text content.

var elmsToReplace = document.querySelectorAll("p mark")

document.querySelector('input').addEventListener('input', updateText)

function updateText(){
  [...elmsToReplace].forEach(elm => elm.innerHTML = this.value)
}
<input> 
<p><mark></mark> went for a run, then <mark></mark> took a nap.</p>
vsync
  • 118,978
  • 58
  • 307
  • 400