ReynierPM
ReynierPM

Reputation: 18660

Toggle button enabled/disabled if at least one input has values or if a select changes the default value

Coming from this related topic where a user leave a solution and it works, I come with a second part where I forgot to mention that the SELECT element has a .select2() applied. If you test a live example here on this Fiddle you'll see how the button#btnBuscar is enable any time a input change and gets values or when SELECT changes the default option but if I delete the values from the INPUTs or choice back the default option in the SELECT then the button is not disabled, where is the error on the solution provided:

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

Upvotes: 1

Views: 788

Answers (1)

PeterKA
PeterKA

Reputation: 24638

Either your could change:

<option selected="selected" value="-1">-- SELECCIONAR --</option>

To:

<option selected="selected" value="">-- SELECCIONAR --</option>

OR adjust the js code to:

$(function(){
    $('select.toSelect2').select2();

    $(':input').on('input change', function () {
        var completed = $(':input').filter(function () {
            return !!this.value && !$(this).is('select') || 
                   (this).is('select') && +this.value > -1;
        }).length > 0;
        $('button#btnBuscar').prop('disabled', !completed);
    });        
});

DEMO

Upvotes: 1

Related Questions