Blade template and radio buttons - select first in foreach loop

南楼画角 提交于 2020-01-06 03:44:38

问题


I have the following Blade template entry, which creates (as part of a table row) a column of radio buttons.

I want to have only the first radio genereated selected, and I want to do this via the PHP, no js post page load.

How do I check if this is the "first" entry in my collection and thus place the string checked as an attribute in the HTML? My latest code permutation is below, but it does not work.

@foreach ($organisationsOwned as $organisationOwned)
    <tr class="organisations-table">
        <td><input type="radio" name="organisations" id="{!! $organisationOwned->id !!}" @if ($organisationsOwned{0}) {!! "checked" !!} @endif></td>
        <td>{!! $organisationOwned->org_title !!}</td>
        <td>{!! $organisationOwned->plan_title !!}</td>
        <td style="text-align: center;">{!! currency_format($organisationOwned->gst_amount) !!}</td>
        <td style="text-align: right;">{!! $organisationOwned->subscription_ends_at !!}</td>
    </tr>
@endforeach

More precisely, here's the line for the input:

<input type="radio" name="organisations" id="{!! $organisationOwned->id !!}" @if ($organisationsOwned{0}) {!! "checked" !!} @endif>

I have tried variations such as:

{{ head($organisationsOwned) ? checked : '' }}>

and

{{ $organisationsOwned{0} ? checked : '' }}>

and even this suggestion shown as a working model of my question:

@if ($organisationOwned == reset($organisationsOwned)) checked @endif

Thanks and happy new year!


回答1:


If you did not specify keys for the elements of $organisationsOwned you can use the element's index to determine if it's the first one:

@foreach($organisationsOwned as $index => $organisationOwned)
  ...
  <td><input type="radio" name="organisations" id="{!! $organisationOwned->id !!}" @if (!$index) {!! "checked" !!} @endif></td>
  ...
@endforeach


来源:https://stackoverflow.com/questions/34554021/blade-template-and-radio-buttons-select-first-in-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!