Ninja Muffin
Ninja Muffin

Reputation: 1

My disable submit if input empty is not working

my disable submit button if input is empty is not working. When i put an input, the submit button still not able to click, it is still disabled. what is wrong here? btw, Im still learning..

<div class="input-group mb-2 mx-sm-2 my-sm-4">
  <div class="form-outline">
    <input type="search" id="" placeholder="North Borneo.." name="valueToSearch" class="form-control" />
  </div>
  <button type="submit" class="btn btn-primary" name="caribtn" disabled="disabled">
    <i class="mdi mdi-magnify"></i>
  </button>
</div>
$(function () {
  $('.button[type="submit"]').keyup(function () {
    var empty = false;

    $('.input[type="search"]').each(function () {
      if ($(this).val().length == 0) {
        empty = true;
      }
    });

    if (empty) {
      $('.button[type="submit"]').attr("disabled", "disabled");
    } else {
      $('.input[type="search"]').removeAttr("disabled");
    }
  });
});

Upvotes: 0

Views: 63

Answers (2)

dw_
dw_

Reputation: 1827

.button or .input class doesn't exist in your context.

Attach a handler to all your search inputs; and inside check if any of them are empty.

$(function() {
 $('input[type="search"]').keyup(function() {
      var empty = false;
      $('input[type="search"]').each(function() {
         if($(this).val().length === 0) {
             empty = true;
         }
      });

      if (empty) {
        $('button[type="submit"]').attr('disabled', 'disabled');
      } else {
        $('button[type="submit"]').removeAttr('disabled');
      }
  });
});
.mdi-magnify::before {content: "magnify-icon";display:inline-block;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group mb-2 mx-sm-2 my-sm-4">
  <div class="form-outline">
    <input type="search" id="" placeholder="North Borneo.." name="valueToSearch" class="form-control" />
  </div>
  <button type="submit" class="btn btn-primary" name="caribtn" disabled="disabled">
      <i class="mdi mdi-magnify"></i>
  </button>
</div>

Upvotes: 0

Harun
Harun

Reputation: 1237

Try it.

$(function() {

    var btnSubmit = $('button[type="submit"]');
    btnSubmit.attr('disabled', 'disabled');

    $('input[name="valueToSearch"]').on('keyup', function() {
        if ($(this).val() !== '') {
            btnSubmit.removeAttr('disabled');
        } else {
            btnSubmit.attr('disabled', 'disabled');
        }
    })

});

Upvotes: 1

Related Questions