Execute functions without the Jquery click event

3

How do I run a particular function without having to wait for the user to click the button?

For example, if input username is empty, add div and when it is not empty the div is destroyed, without any button, without clicking.

    
asked by anonymous 19.07.2015 / 18:41

3 answers

3

I find it unnecessary to use JQuery in this case, you could get the desired result using only JavaScript pure ....

Well, anyway a workaround 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 in the onkeyup , this way the verification 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

    
19.07.2015 / 20:18
3

I would solve the problem you mentioned using the onkeypress event in the input or from jQuery with the keypress method if it is empty or not empty, eg

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 .remove method 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, eg

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

I hope it has helped you, any questions are here.

    
19.07.2015 / 19:32
3

Another example, I hope it helps, this uses the remove method and add 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");*/
                }
        });
    });
    
19.07.2015 / 20:01