Thomas Hodge
Thomas Hodge

Reputation: 13

Retaining user selected option from a select field in Laravel on Form method GET

I'm trying to retain a selected option in a select field after the user submits.

There are a number of related questions that I have looked at, but none of the answers are working for me. (So, yes, I understand this may be a 'duplicate' question of sorts...)

I have tried a number of different solutions that have been given to other similar queries, including using if(isset(...)) to check if a value had been submitted, and have also tried @if(old('value') == (value) (as shown in the snippet below), but none work.

My form code is below...

<select name="score" id="score">
<option value="default">Select a Finish</option>
@foreach ($scoreLeft as $score)
<option value="{{ $score->score }}" @if (old('score') == $score->score) selected @endif>
{{ $score->score }}
</option>
@endforeach
</select><br/>
<input type="submit" class="btn btn-primary" />
</form>

I think that the issue with the above is that the '>' in @if (old('score') == $score->score) is being seen as a tag close, but I can't see any other way of accessing the 'score' within the '$score' variable. I've tried wrapping this in quotes, and in blades, and neither fix the issue.

I have also tried @if (old('score') != 'default') selected @endif, but on submit the 'selected' value is set as the very first value in the variable.

For further information, the reason that I want to retain this input is that I need the user to be able to input a number in to a separate field (within in a separate form) to subtract from the 'selected' value.

I do anticipate answers of 'do it with JavaScript', however if there is a way of doing this with PHP I'd prefer it.

Please let me know if any additional information is needed from me

Upvotes: 0

Views: 273

Answers (1)

ankit patel
ankit patel

Reputation: 1918

did you inspect that select element ?

you just need to change

<option value="{{ $score->score }}" {{ (old('score') == $score->score) ? "selected=selected" : "" }} >

Upvotes: 1

Related Questions