ABHISHEK JETANI
ABHISHEK JETANI

Reputation: 19

How to customize multiselect input in Laravel to show option names or number of selected options?

I am using a multiselect dropdown in a Laravel project, and I need to customize its behavior. Specifically, I want the input field to show the following:

  1. If fewer than 4 options are selected, display the names of the selected options in the input field (e.g., "Option 1, Option 2").

  2. If more than 3 options are selected, display a summary like "X selected" (e.g., "4 selected").

Here's the HTML code I’m using for the multiselect:

<select class="multiselect @error('age_group_id') is-invalid @enderror" placeholder="Select event for" name="age_group_id[]" id="age_group_id" multiple>
@foreach ($age_groups as $ag)
    <option value="{{ $ag->id }}" {{ in_array($ag->id, old('age_group_id', ($is_update ? $event->age_group_id : []))) ? "selected" : "" }}>
        {{ $ag->name }}
    </option>
@endforeach

I'm using the Bootstrap Multiselect (or Select2, if that's your case) library, and I want to ensure the following behavior:

I’ve tried modifying the buttonText or templateSelection functions in the multiselect configuration, but I’m not sure how to implement this properly.

Can anyone provide an example or solution to help me achieve this behavior?

Expected Behavior:

Additional Information:

Upvotes: -2

Views: 40

Answers (1)

ABHISHEK JETANI
ABHISHEK JETANI

Reputation: 19

This is working perfectly for me, but I'd like to add an alternative solution using the numberDisplayed option available in Bootstrap Multiselect. Here’s a working solution using that parameter:

$('.multiselect').multiselect({
    numberDisplayed: 4,  // This will display up to 4 selected items
});

In this case, numberDisplayed: 4 ensures that no more than 4 selected options are shown in the input field. If you select more than 4 options, the input field will display the summary text (e.g., "5 selected").

The numberDisplayed option simplifies the implementation if you only want to limit the number of selected options displayed

Thank you!

Upvotes: 0

Related Questions