skip to Main Content

I have a form with among others this 2 selects :

<div class="form-group">
    <select name="yul_log_christmas_serving_id" id="yul_log_christmas_serving_id" class="form-control">
        <option value="">{{ __('# Personnes | Taille') }}</option>
        @foreach($yul_log_christmas_servings as $serving)
            <option style="color:#6c757d" value="{{ $serving->id }}" {{ $party_loaf_serving_id == $serving->id ? 'selected' : '' }}>{{ $serving->servings }}</option>
        @endforeach
    </select>
</div>

and

<div class="form-group">
    <select name="yul_log_christmas_flavor_id" id="yul_log_christmas_flavor_id" class="form-control">
        <option value="">{{ __('Saveur') }}</option>
        @foreach($frozen_flavor as $flavor)
            <option style="color:#6c757d" value="{{ $flavor->id }}">{{ $flavor->flavor }}</option>
        @endforeach
    </select>
</div>

This is the submit button:

<div class="form-group">
    <button class="btn btn-sm" id="add-product" disabled>{{ __('Ajouter au Panier') }}</button>
</div>

I have coded the following script to make that the #add-product button is only available if the 2 selects are populated:

<script>
    // Yul Log
    if($("#form-category-id").val() == 11 ) {       
$('#yul_log_christmas_serving_id','#yul_log_christmas_flavor_id').on('change', function () {
            $('#add-product').prop('disabled', !$(this).val());
        }).trigger('change');
    }
</script>

This doesn’t work. As soon as the first select is populated the button is enabled.

So I have tried this:

<script>
    // Yul Log
    if($("#form-category-id").val() == 11 ) {
        $('[id^=yul_log]').on('change', function () {
            $('#add-product').prop('disabled', !$(this).val());
        }).trigger('change');
    }
</script>

Result is the same.

Would appreciate some jQuery expertise, since I am stuck.

2

Answers


  1. you have to check both of select to disable/enable the button, so you can add the same event to both of select like this :

    ...
    $('#yul_log_christmas_serving_id, #yul_log_christmas_flavor_id').on('change', function() {
        selectChanged();
    });
    
    function selectChanged() {
        let val1 = $('#yul_log_christmas_serving_id').val();
        let val2 = $('#yul_log_christmas_flavor_id').val();
        $('#add-product').prop('disabled', (val1 === "" || val2 === ""));
    }
    ...
    
    Login or Signup to reply.
  2. You are checking only for the currently changed select. You need to change both:

    let christmasServing = $('#yul_log_christmas_serving_id');
    let christmasFlavor = $('#yul_log_christmas_flavor_id');
    $('#yul_log_christmas_serving_id','#yul_log_christmas_flavor_id').on('change', function () {
        $('#add-product').prop('disabled', !(christmasServing.val() && christmasFlavor.val()));
    }).trigger('change');
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search