Run functions without the Jquery click event

Asked

Viewed 1,332 times

3

How do I execute a certain function without having to wait for the user to click the button?

For example, if the input username is empty, add a div and when it is no longer empty div is destroyed, this without any button, without having to click.

  • I don’t know if I got it right, but I think you’re looking for the job keypress. I created a little fiddle here, see if this is what you’re looking for: http://jsfiddle.net/gustavox/aVyuB/101/ ?

  • Basically, need bind for another event - click is just one of several.

3 answers

3

Would solve the problem you mentioned using the onkeypress event in input or from jQuery with the keypress method if it is empty or not empty, example:

HTML:

<input type="text" id="inputText">
<div id="conteudo">

Javascript:

$('#inputText').keypress(function (){
    if (this.value != ''){
        $('#conteudo').innerHTML = '';
    } else {
        $('#conteudo').innerHTML = 'O campo não está preenchido';
    }
});

If you prefer you can use the method . remove when it is not empty, but when it is empty again the div will not be found and consequently will not be filled when the user leaves the field empty, example:

$('#conteudo').remove();

I hope it helped you, any doubt we are here.

3

Another example, I hope it helps, this uses the remove and add method a Class and the keyup function.

CSS:

.notempty{
background-color:#0F0;
width:20px;
height:20px;
}

.empty{
background-color:#F00;
width:20px;
height:20px;
}   

HTML:

    <input type="text" />
    <p id="warning"></p>     

JQUERY:

$(document).ready(function(){
        $("#warning").addClass("empty");
            $(":text").keyup(function(){

                if(this.value != '')
                {
                    $("#warning").removeClass("empty");
                    /*remova addclass e terá o efeito esperado
                    $("#warning").addClass("notempty");*/
                }
        });
    });

3


I find it kind of unnecessary to use Jquery in that case, you could get the desired result using only JavaScript pure....

Good, anyway an alternative solution using only JavaScript, without Jquery

window.sumirDiv = function(){
  var campo = document.getElementById("campo").value;

  if(campo.length < 1) div.style.display = "block"; 
  else div.style.display = "none"; 
}
<input id="campo" type="text" onkeyup="sumirDiv()" style="float:left"/>
<div id="div" style="display:block">*Campo Obrigatorio</div>


I changed the function to check on onkeyup, this way the check is only done after the key is released.

onkeydown -> function is triggered when the user is pressing a key

onkeypress -> function is triggered when the user presses a key

onkeyup -> function is triggered when the user releases a key

Browser other questions tagged

You are not signed in. Login or sign up in order to post.