php - Use data attributes in laravel form select

995

How would i add a data attribute to a laravel{{Form::select}} array?

For example, I want each of my options to look like this

<option value="1" data-days="182">6 Months</option>
<option value="2" data-days="365">1 Year</option>

How do I add the data attribute in the following select array?

Days Table

id | days |   name
1  |  182 |   6 Months
2  |  365 |   1 Year

View

{{Form::select('amount_of_days', $days, null, ['placeholder' => 'Amount of days'])}}
370

Answer

Solution:

The best way to set the custom value to the form::select is by using the attribute parameter of form::select function.

controller.php

$contact_options = Contact::all();

$contact_attributes = $contact_options->mapWithKeys(function ($item) {
    return [$item->id => ['data-otherInfo' => $item->otherInfo]];
})->toArray();

$contact_options = $contact_options->pluck('name', 'id')->toArray();

blade.php

{!! Form::select('contact_id', $contact_options, old('contact_id', null), ['class'=>"form-control", 'id'=>"contact_id", 'required' => 'required'], $contact_attributes) !!}
796

Answer

Solution:

For this requiment you need to create the<option> with loop and simply html

<select name="amount_of_days" placeholder="Amount of days">
    @foreach($days as $val)
        <option value="{{ $val['id'] }}" data-days="{{ $val['days'] }}"> {{ $val['name'] }}<option>
    @endforeach
</select>

People are also looking for solutions to the problem: Can't get node's text with XPATH from my XML using PHP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.