Home » Jquery » jquery – Enable submit button with validation

jquery – Enable submit button with validation

Posted by: admin February 22, 2020 Leave a comment

Questions:

Here is my code.
The problem I encountered is how do I make the submit button work only when it is 10?

<input type="text" name="qty>
<input type="submit" name="proceedbtn" value="PROCEED" id="button">

<script>
   $(document).ready(function(){
        $('input[id="button"]').attr('disabled',true);
        $('input[id="qty"]').on('keyup',function(){
            if($(this).val() == 10)
            $('input[id="button"]').attr('disabled',false);
    });
});
</script>

How do i fix it?

How to&Answer:

I have made some corrections in your code, and now its working. The problem in your code was, you were writing key up event on ID but haven’t assigned any id to input box, but you had name property so instead of id I used that name property as a selector for key up event.

$(document).ready(function() {
  $('input[id="button"]').attr('disabled', true);
  $('input[name="qty"]').on('keyup', function() {
    if ($(this).val() == 10) {
      $('input[id="button"]').attr('disabled', false);
    } else {
      $('input[id="button"]').attr('disabled', true);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="" name="qty" />
<input type="submit" name="proceedbtn" value="PROCEED" id="button" />

Answer:

Please check, I have updated your code

  $(document).ready(function(){
        $('input[id="button"]').attr('disabled',true);
        $('input[name="qty"]').keyup(function(){
            if($(this).val() == 10){
            $('input[id="button"]').removeAttr('disabled');
            }
            else{
              $('input[id="button"]').attr('disabled',true);
            }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="qty">
<input type="submit" name="proceedbtn" value="PROCEED" id="button">

Answer:

I have made some editions on your code and IT WORKS PERFECTLY!

$(document).ready(function() {
        $('#button').attr('disabled', true);
        $('input[name="qty"]').on('keyup', function () {
            if ($(this).val() == 10) {
                $('#button').attr('disabled', false);
            }else {
                $('#button').attr('disabled', true);
            }
        });
    });
<input type="text" name="qty">
<input type="submit" name="proceedbtn" value="PROCEED" id="button">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>