Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the current value of an input field with innerHTML?

I would like to get HTML of an editable div. It contains text and an <input> tag. See:

document.body.addEventListener('click', () => {
  console.log(document.getElementById('content').innerHTML);
})
body {
  height: 100vh;
}
<div id="content" contentEditable="true">
  I want <input type="number" value="3"> candies.
</div>

My problem is <input type="number" value="3">. When I update the value of the input field, I still get the default value.

So how can I get the live value of the input field?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am not NOT looking for the value of the input field. The output should be the full content of div#content as a string.

>Solution :

Changing the value of an input doesn’t affect the value attribute in the HTML, because that’s used for its default value, not the current value.

You’ll need to merge the value of the input into the innerHTML of the DIV to get the result you want.

document.body.addEventListener('click', () => {
  let html = document.getElementById("content").innerHTML;
  let value = document.getElementById('input').value;
  new_html = html.replace(/value="\d+"/, `value="${value}"`);
  console.log(new_html);
})
body {
  height: 100vh;
}
<div id="content" contentEditable="true">
  I want <input type="number" value="3" id="input"> candies.
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading