Search code examples
javascripthtmlweb-componentsalesforce-lightning

Not able to fetch updated content from div contenteditable on keyup event


I am implementing this using lightning-web-components.

I am using <div contenteditable> to apply different styling to multiple lines.

Here, assetSerialNumber and assetLocation gets populated in connectedcallback() method in js. I am using divTextarea in class to make div look like textarea which is working fine.

.html file

<div id="divcontenteditable" class="divTextarea slds-textarea" contenteditable onkeyup={handleChange}> 
   <p>Device request:  {assetSerialNumber}</p>
   <p>Device location {assetLocation}</p>
</div>

.js file

handleChange(event) {
        var input = this.template.querySelector(".divTextarea");
        console.log(input.innerText);
        console.log(input.textContent);
    }

Scenario 1: If I am adding any text to either of <p> tags under <div contenteditable>, handleChange method is able to retrieve updated text values.

Scenario 2: If I press ENTER and starts typing, I am not able to get updated text. Everytime ENTERis pressed, a new <p> is added under <div contenteditable> like below and handleChange method still returns the original text`

<div id="divcontenteditable" class="divTextarea slds-textarea" contenteditable onkeyup={handleChange}> 
       <p>Device request:  {assetSerialNumber}</p>
       <p>Device location {assetLocation}</p>
       <p>New text</p>
 </div>

How can I achieve scenario 2 i.e. to fetch updated content when text is added in a new line.


Solution

  • I was able to get updated content from div with below approach. I removed default text from html file and added those in innerHTML in js file. Then I was able to get updated content from input.textContent.

    html file

    <div id="divcontenteditable" class="divTextarea slds-textarea" contenteditable 
    onkeyup={handleChange} lwc:dom="manual"></div>
    

    js file:

    let divTextarea = this.template.querySelector('.divTextarea');
    divTextarea.innerHTML = '<p>'+Device request:+' '+this.assetSerialNumber+'</p>'+'<p>'+Device location+' '+this.assetLocation+'</p>';
    

    and then onkeyup event will handled like below:

    handleChange(event) {
       var input = this.template.querySelector(".divTextarea");
       console.log(input.textContent);
    }