简体   繁体   中英

JS: if innerhtml is empty, change innerhtml to something. HOW?

i'm new to js so i have a simple html element that has contenteditable="true" which i'm using as an input box. i want the innerhtml to change to "CAN'T BE EMPTY" when the user has typed nothing in the input box ( " " ) and apparently it doesn't work, any tips on how i can do it? this is my code (which is not working):

HTML: <p contenteditable="true" id="myparagraph">Input</p>

JS:

 if(document.getElementById("myparagraph").innerHTML == ""){
 document.getElementById("myparagraph").innerHTML = "CAN'T BE EMPTY";}

i've also tried using the LENGTH property, but didn't work either:

    var plength = document.getElementById("myparagraph").innerHTML;
        var plength2 = plength.length;
if(plength2 == 0){
     document.getElementById("myparagraph").innerHTML = "CAN'T BE EMPTY";}

It's not empty. It's got a value of Input according to your HTML.

If you want to change the value when the user edits, you need to attach an event listener :

 document.getElementById('myparagraph').addEventListener('input', (e) => { if (e.target.textContent.trim() === '') { e.target.textContent = 'Cannot be empty'; } })
 <p contenteditable="true" id="myparagraph">Input</p>

Note that I changed the logic from using innerHTML to using textContent because otherwise remaining empty HTML tags can prevent the warning from triggering. (Firefox, for example inserts a <br> when there is no content.)

It would be better to display the warning anywhere than the content of the element you're trying to check. Add an event listener to the paragraph element. In the handler get the textContent from the element, and then show/hide the warning depending on whether that text is empty.

 const para = document.querySelector('#para'); const warning = document.querySelector('#warning'); para.addEventListener('input', handleInput, false); function handleInput() { const text = this.textContent; warning.textContent = text ? '' : 'Cannot be empty'; }
 #para { border: 1px solid #565656; padding: 0.5em; } #warning { color: red; }
 <p contenteditable="true" id="para">Input</p> <p id="warning"></p>

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