enable input button

2

The code I have to validate the button does not work:

$(document).ready(function(){  
  $("#sendCat").prop('disabled', true);
  if ($('#cat').val()!= "") {
    $("#sendCat").prop('disabled', false);  
  }
 
});
<form action="proc_cat.php" method="post">
        <div class="input-field col s5">
            <input id="cat" name="name_cat" type="text">
            <label>Categoria:</label>
        </div>
        <div class="input-field col s5">
            <input name="sub_cat" type="text">
            <label>SubCategoria</label>
        </div>
        <div class="input-field col s2">
            <button id="sendCat" class="btn">Adicionar</button>
        </div>
    </form>
    
asked by anonymous 20.03.2017 / 20:15

2 answers

3

Places the disabled attribute directly in the HTML to avoid waiting for JavaScript.

Then joins an event osculator to find out when a change in #cat occurs. It could look like this:

$(document).ready(function(){  
  $('#cat').on('input', function(){
    $('#sendCat').prop('disabled', !this.value);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formaction="proc_cat.php" method="post">
        <div class="input-field col s5">
            <input id="cat" name="name_cat" type="text">
            <label>Categoria:</label>
        </div>
        <div class="input-field col s5">
            <input name="sub_cat" type="text">
            <label>SubCategoria</label>
        </div>
        <div class="input-field col s2">
            <button id="sendCat" disabled class="btn">Adicionar</button>
        </div>
    </form>
    
20.03.2017 / 20:33
2

To enable the correct button is to put some event in #cat , as change for example:

$(document).ready(function() {
  $("#sendCat").prop('disabled', true);
});

$("#cat").change(function(a) {
  let botao = $("#sendCat");
  $(this).val() ? botao.prop('disabled', false) : botao.prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formaction="proc_cat.php" method="post">
  <div class="input-field col s5">
    <input id="cat" name="name_cat" type="text">
    <label>Categoria:</label>
  </div>
  <div class="input-field col s5">
    <input name="sub_cat" type="text">
    <label>SubCategoria</label>
  </div>
  <div class="input-field col s2">
    <button id="sendCat" class="btn">Adicionar</button>
  </div>
</form>
    
20.03.2017 / 20:18