How to get selected value from database in Select Option - Laravel

2544 views php
6

I have a select option displaying numbers from 1-100. I am able to save a number to my database say 70. During retrieval, how can compare the figure in the database (70) to the list of numbers in the select option to get 70 selected ?

Controller

public function getMarks()
{
 get_stored_number = Figures::where('site', Auth::user()->site);
 return $get_stored_number->pass_mark // this return the 70
}

HTML

   <div class="row">
   <div class="col-xl-3 col-lg-12 col-md-12 mb-1">
   <fieldset class="form-group">
   <label for="squareText">Total Pass Mark</label>
   <select class="form-control total" name="totalpass"  class="form-control" required >
   </select>                        
   </fieldset>
   </div>

  <script type="text/javascript">
$(document).ready(function() {
    var $select = $(".total");
    for (i=1;i<=100;i++){
        $select.append($('<option></option>').val(i).html(i))
    } 
   });
   </script>

How do i check if 70 is included in the list of numbers in the select option to get it selected ?

answered question

1 Answer

13

This can be done with php

<select class="form-control total" name="totalpass"  class="form-control" required >
@for( $i = 1; $i <= 100; $i++ )
  <option value="{{$i}}" {{($student->getMarks() == 70)? 'selected':''}}>{{$i}}</option>
@endfor

This is considering $student is the object calling the method getMarks()

If you want to change the comparison value to whichever number you want you can replace the <option> field given above with the following

<option value="{{$i}}" {{($student->getMarks() == $your_marks)? 'selected':''}}>{{$i}}</option>

This is considering the desired value is saved in $your_marks variable

posted this

Have an answer?

JD

Please login first before posting an answer.