Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

263
Views
JS: si innerhtml está vacío, cambie innerhtml a algo. ¿CÓMO?

soy nuevo en js, así que tengo un elemento html simple que tiene contenteditable="true" que estoy usando como cuadro de entrada. Quiero que el HTML interno cambie a "NO PUEDE ESTAR VACÍO" cuando el usuario no haya escrito nada en el cuadro de entrada (" " ) y aparentemente no funciona, ¿algún consejo sobre cómo puedo hacerlo? este es mi código (que no funciona):

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

JS:

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

También intenté usar la propiedad LENGTH, pero tampoco funcionó:

 var plength = document.getElementById("myparagraph").innerHTML; var plength2 = plength.length; if(plength2 == 0){ document.getElementById("myparagraph").innerHTML = "CAN'T BE EMPTY";}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

No está vacío. Tiene un valor de Input de acuerdo con su HTML.

Si desea cambiar el valor cuando el usuario edita, debe adjuntar un detector de eventos :

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

Tenga en cuenta que cambié la lógica de usar innerHTML a usar textContent porque, de lo contrario, las etiquetas HTML vacías pueden evitar que se active la advertencia. (Firefox, por ejemplo, inserta un <br> cuando no hay contenido).

about 4 years ago · Juan Pablo Isaza Report

0

Sería mejor mostrar la advertencia en cualquier lugar que no sea el contenido del elemento que está tratando de verificar. Agregue un detector de eventos al elemento de párrafo. En el controlador, obtenga el textContent de texto del elemento y luego muestre/oculte la advertencia dependiendo de si ese texto está vacío.

 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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!