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:
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.
- Instead of appending
=
you need to reassign=
the input's value to the label. (a = 1
actually meansa = a 1
). - Don't use inline styles. Put CSS in an external stylesheet.
- Don't use inline event listeners, use
addEventListener
instead. This then also allows you to use the element the listener is bound to asthis
inside your event handler function. - Don't listen to
keyup
;input
elements offer aninput
event which is the far superior event here. - Never assign unsanitized user input to
innerHTML
!! UsetextContent
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>