Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

I want to keep the select option selected once i submitted the form. I'm using Laravel 7 with Bootstrap

Here's the View Code: also I'm passing the variable to be selected by compact, but this technique does'nt work

<select class="form-control" name="month">
    @foreach ($cement_cmonths as $cement_cmonth)
        <option {{$month == $cement_cmonth->cmonth ? "selected" : ""}} value=" 
        {{$cement_cmonth->cmonth}}">{{$cement_cmonth->cmonth}}</option>
    @endforeach 
</select>

The $month is the selected variable to remain selected, i'm passing it through compact.

question from:https://stackoverflow.com/questions/65861499/i-want-to-keep-the-select-option-selected-once-i-submitted-the-form-im-using-l

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your conditional is failing:

{{ $month == $cement_cmonth->cmonth ? "selected" : "" }}

The above is not evaluating to true hence the selected attribute not being applied to any of your options.

This means your $month and $cement_cmonth->cmonth values are not equal. This could be because they are genuinely not the same ('jan' != 'feb') or it could be the values are the same but the casing differs.

As you are using strings you need to be careful of character casing as == is case sensitive.

The following evaluates to false:

'jan' == 'Jan'

To avoid this issue, use strcasecmp:

{{ strcasecmp($month, $cement_cmonth->cmonth) === 0 ? "selected" : "" }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...