Aidan Young
Aidan Young

Reputation: 614

JavaScript set content editable value to variable

I have a content editable <p> tag in html and a button. I'm wondering how I can make it so that when the button is pressed, the variable called content will be set to the value inside of the content editable p tag . For example, if you type in the <p> tag "Hello world" and press the button, the variable content will have a value of "Hello world"

Code:

<p contenteditable="true">
hi
</p>

<button onclick="update()">
Update
</button>

<script>
function update() {
var content = "content of content editable"
console.log (content)
}
</script>

Upvotes: 1

Views: 1220

Answers (1)

BGPHiJACK
BGPHiJACK

Reputation: 1397

You'd start by wanting to avoid any issues by using inline-script. So first things first get rid of the onclick and give each element you'll be using for this operation a specific ID.

Next we'll querySelect the element/button and apply an event listener for our button to know when it's clicked to react appropriately.

Below is an example. It's a bit of a duplication but should be okay.

function update() {
  return "content of content editable";
}
// Select the submit button
document.querySelector("#editable_submit").addEventListener("pointerup", (event) => {
  // Button Clicked
  document.querySelector("#editable_box").innerText = update(); // Update Editable Box
}, {
  passive: true
});
<p id="editable_box" contenteditable="true">
  hi
</p>

<button id="editable_submit">
Update
</button>

Upvotes: 2

Related Questions