简体   繁体   中英

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?

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.

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>

The value isn't part of the HTML. It's a live property on the DOM. You need to fetch the actual <input> element and observe its value property.

Instead of getElementById , use querySelector which takes a more robust selector to identify the target element. In this case that target element is the <input> inside the #content element. For example:

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

Like @Barmar said the attribute will not be updated only the internal DOM Property.

But you can manual update it on change like this:

 document.querySelector('input').addEventListener('input', (e) => { e.target.setAttribute('value', e.target.value); }); 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>

I don't see why you can't just add another id tag to your input element, like <input id="contentInput" type="number" value="3">

and then grab the inner HTML with this Id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM