Fill old html select field in laravel on error

I have a form with selected input, validation is correct, but after failure the select box does not fill the old value here is my select box

  <div class="control-group">
   <label class="control-label">Gender :</label>
    <div class="controls">
        <select  name="gender" value= "{{ Input::old('gender') }}">
            <option>Select</option>

                <option value="M">Male</option>
                <option value="F">Female</option>
        </select>
    </div>
</div> 

      

how can i solve this?

+3


source to share


4 answers


If you don't want to use Laravel Form build, you need to do it like this:



 <div class="control-group">
   <label class="control-label">Gender :</label>
    <div class="controls">
        <select  name="gender">
            <option>Select</option>

                <option value="M" @if (Input::old('gender') == 'M') selected="selected" @endif>Male</option>
                <option value="F" @if (Input::old('gender') == 'F') selected="selected" @endif>Female</option>
        </select>
    </div>
</div> 

      

+10


source


It has to do with the HTML select element.

If you want to assign any default value to the select element use the selected attribute = "selected" for that particular option, otherwise it will display the first parameter value by default.



<select  name="gender">
    <option>Select</option>
        <option value="M" @if (Input::old('gender') == 'M') selected="selected" @endif>Male</option>
        <option value="F" @if (Input::old('gender') == 'F') selected="selected" @endif>Female</option>
</select>

      

+1


source


I personally find this code to be cleaner. There is no right or wrong here, I can understand why some would prefer the Laravel @if @ endif statements, I just think they look too visually disturbing.

<option {{ old('gender')=='male' ? 'selected="selected"' : '' }}>Test option</option>

      

+1


source


So I am very dynamic.

<select id="gender" name="gender">
    <option>Select</option>
        <option value="M">Male</option>
        <option value="F">Female</option>
</select>

<script>
    var currentGender = null;
    for(var i=0; i!=document.querySelector("#gender").querySelectorAll("option").length; i++)
    {
        currentGender = document.querySelector("#gender").querySelectorAll("option")[i];
        if(currentGender.getAttribute("value") == "{{ old("gender") }}")
        {
            currentGender.setAttribute("selected","selected");
        }
    }
</script>

      

+1


source







All Articles