Search code examples
jqueryhtmlinputtyping

Disable/Enable submit button not working on mobile classes


I have a search form with 3 inputs (2 texts and one dropdown select), and I made a jQuery pre-validation code that disable the submit button unless something is typed on those inputs. Code looks like this:

// Search button is disabled until something is typed.
$(document).ready(function () {
 $('input[type="submit"]').prop('disabled', true);
 $('input[type="text"]').keyup(function () {
   if ($(this).val() != '') {
      $(':input[type="submit"]').prop('disabled', false);
   } else {
      $(':input[type="submit"]').prop('disabled', true);
   }
});
 $('#dropdown').on("change", function () {
   if ($(this).val() == '') {
      $(':input[type="submit"]').prop('disabled', true);
  } else {
      $(':input[type="submit"]').prop('disabled', false);
  }
 });
});

The code works perfectly on web/desktop. Then, I wanted to personalize the page for mobile devices, so I've added the exactly same form with those 3 inputs into the d-block d-sm-none Bootstrap 4 class - the div will be shown only when user is on mobile.

The code is responding while on mobile, it does its job on first two inputs (text ones), but the dropdown select is not doing the trick. Even if I select something from the list, the button is still disabled.

The dropdown code looks like this in both version (desktop and mobile):

<select class="custom-select" name="status" id="dropdown">
<option selected="selected" value="">Find by status</option>
@foreach($status as $sts)
<option value="{{$sts->id}}">{{$sts->name}}</option>
@endforeach
</select>

Any ideas? Thank you!


Solution

  • You need to use class instead of id to select the dropdown :

    $(document).ready(function () {
     $('input[type="submit"]').prop('disabled', true);
     $('input[type="text"]').keyup(function () {
       if ($(this).val() != '') {
          $(':input[type="submit"]').prop('disabled', false);
       } else {
          $(':input[type="submit"]').prop('disabled', true);
       }
    });
     $('.custom-select').on("change", function () {
       if ($(this).val() == '') {
          $(':input[type="submit"]').prop('disabled', true);
      } else {
          $(':input[type="submit"]').prop('disabled', false);
      }
     });
    });
    

    When you use $('#dropdown') your code will be only apply on the first Select in the DOM