Skip to content Skip to sidebar Skip to footer

Enable Button (or Any Element) If At Least One Input Has Value

I'm need to enable a button (and perhaps other elements on the form in the near future) if at least one of the input element has values. I'm using BootstrapValidator as a main vali

Solution 1:

    $(function() {
            $(':text').on('input', function() {
                if( $(':text').filter(function() { return !!this.value; }).length > 0 ) {
                     $('button').prop('disabled', false);
                } else {
                     $('button').prop('disabled', true);
                }
            });
    });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form>
First name: <inputtype="text"name="firstname"><br>
Last name: <inputtype="text"name="lastname"><br><buttondisabled="disabled">Submit</button></form>

Update

To expand this so it works with other form elements (excluding radios and checks) you can change :text to :input. And the code can be shortened to the following:

$(function() {
    $(':input').on('input', function() {
        var completed = $(':input').filter(function() { return !!this.value; }).length > 0;
        $('button').prop('disabled', !completed);
    });
});

Solution 2:

Each input element has an event called change attached to it. I would add a function to run whenever this is done.

If you really want to run code whenever even one letter is added to a field, you can instead use the event known as input (be sure to check the performance of any code like this though, as it will be triggered alot!)

Although, there is much less browser support for the input event than the change one.

$('input.some_input').on('change', function() {
  if ($(this).val().length > 0) { 
    alert('woot! text!');
  }  
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputclass='some_input'value='test' />

Post a Comment for "Enable Button (or Any Element) If At Least One Input Has Value"