Home > Blockchain >  Why my function breaks when I input a large text value?
Why my function breaks when I input a large text value?

Time:12-21

I made a function to get a text input value and show it in a label, and it actually works, but when input a large value as "Engenheiro", i get this:

Label breaking insanely

Here's my code:

  function funcaoProfissao()
    {
        var a = document.getElementById('profissao')
        var b = document.getElementById('lblprofissao');
        b.innerHTML  = a.value;
    }
                      <input  type="text"  style="font-size: 22pt; color:grey;" name="profissao" id="profissao" onkeyup="funcaoProfissao()"><br>  


 <h3 >Bacana! Conhecemos e damos consultoria para muitos 
                    <label  id="lblprofissao"></label> (es/s) que <br>
                    também priorizam viagens e férias como você!! :D
               </h3>

I'm new to stackoverflow, so I'm previously sorry for any error or mistake on my question.

CodePudding user response:

There is 5 problems with your code. Only the first is directly responsible for your problem; so you learn a little more from asking here, I've also added another 4 problems with your code, along with an explanation.

  1. Instead of appending = you need to reassign = the input's value to the label. (a = 1 actually means a = a 1).
  2. Don't use inline styles. Put CSS in an external stylesheet.
  3. Don't use inline event listeners, use addEventListener instead. This then also allows you to use the element the listener is bound to as this inside your event handler function.
  4. Don't listen to keyup; input elements offer an input event which is the far superior event here.
  5. Never assign unsanitized user input to innerHTML!! Use textContent for this instead, and use innerHTML only if the string you want to assign should be parsed as HTML.

function funcaoProfissao() {
  document.getElementById('lblprofissao').textContent = this.value;
}

document.getElementById('profissao').addEventListener('input', funcaoProfissao);
#profissao {font-size: 22pt; color:grey;}
<input  type="text" name="profissao" id="profissao" ><br>
<h3>Bacana! Conhecemos e damos consultoria para muitos
  <label id="lblprofissao"></label> (es/s) que <br> também priorizam viagens e férias como você!! :D
</h3>

CodePudding user response:

Instead of = use only = like this b.innerHTML = a.value to display value:

function funcaoProfissao() {
  var a = document.getElementById('profissao')
  var b = document.getElementById('lblprofissao');
  b.innerHTML = a.value;
}
<input  type="text" style="font-size: 22pt; color:grey;" name="profissao" id="profissao"
onkeyup="funcaoProfissao()"><br>


<h3 >Bacana! Conhecemos e damos consultoria para muitos
<label  id="lblprofissao"></label> (es/s) que <br>
também priorizam viagens e férias como você!! :D
</h3>

  • Related