enable input button

Asked

Viewed 587 times

2

The code I have to validate the button doesn’t 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>

  • 1

    You have to have an event receiver to check for changes, that’s what you’re looking for? $('#cat').on('change', function(){...

  • @Sergio, it worked, however have two problems with this method, when I delete data from the input field and becomes empty, the button does not disable again and is only enabled when I exit the input, it would be interesting to enable the button to type the first letter in the input.

  • I answered this in my reply below, using the event input, take a look.

2 answers

3


Puts the attribute disabled directly in HTML to avoid waiting for Javascript.

Then assemble an event osculator to learn when a change occurs in the #cat. It could be so:

$(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>
<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" disabled class="btn">Adicionar</button>
        </div>
    </form>

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>
<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>

Browser other questions tagged

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