Check if automatically filled field is "True" jQuery

Asked

Viewed 156 times

3

I have the following fields

<input type="text" value="" name="campo" id="campo">
<input type="text" value="" name="campoRecebeDados" id="campoRecebeDados">

And the next jQuery:

$(document).ready(function(){ 

    function setar_valor(){
        var campo = $("#campo").val();
        $("#campoRecebeDados").val(campo);
    }

    $(document).on("keyup", "#campo", setar_valor);   

});

At the moment I’m using keyup, which would be in the case if the campo is completed, it copies the value to the campoRecebeDados, but as I know (via code) that the campoRecebeDados was filled out?

I thought I’d make:

if($("#campoRecebeDados")==true){
    alert('Preenchido')
}

However, if I do it this way, it will never be true because the fill value="" field will always be the initial stage, not the one set. (This is seen in the source code);

In this case I already filled a previous field, which filled this, but as you can see value="" remains unchanged.

inserir a descrição da imagem aqui

2 answers

3


Then you’d have to change the attribute value, which is an input property:

$("#campoRecebeDados").attr("value", campo);

The .val() does not change this property, it just takes or changes what is inside the field, and that is enough to know whether the field has been filled or not.

And to check if the input has anything, would be enough:

if($("#campoRecebeDados").val()){
    // possui algum valor
}

In the case of inputs, if the value initial is empty, need not even put value="", because the value already comes empty by default.

Example based on your code:

$(document).ready(function(){ 

    function setar_valor(){
        var campo = $("#campo").val();
        $("#campoRecebeDados").val(campo);

      if($("#campoRecebeDados").val()){
         console.log("tem valor");
      }else{
         console.log("não tem valor");
      }
    }

    $(document).on("keyup", "#campo", setar_valor);   

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="campo" id="campo">
<input type="text" name="campoRecebeDados" id="campoRecebeDados">

  • In this case, I needed the check to be automated.. ie filled, it passed to the other field and automatically check whether the other field was filled or not...

  • I didn’t understand the purpose, but I made a change in the answer. I don’t know if that’s what you want.

2

Try

if( $("#campoRecebeDados").val().length > 0 ){}

Or

if( $("#campoRecebeDados").val() != "" ){}
  • The problem is that in the val it will never be the value set through jQuery, it will always be in the initial stage. That is the value=""

Browser other questions tagged

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