Hilario M.
Hilario M.

Reputation: 13

How to display a preselected value in a dropdown without 'onchange'

Currently I have a dropdown in my edit.blade.php

<div class="md-form">
   <select id="estado_civil" name="estado_civil" class="mdb-select validate" onchange="editar('estado_civil',$(this).val());">
      <option value=""></option>
      <option value="1">Soltero(a)</option>
      <option value="2">Unido(a)</option>
      <option value="3">Casado(a)</option>
   </select>
</div>

I needed the dropdown to select/display the value the user had previously chosen and stored in the database. I achieved this using JQuery:

$(document).ready(function() {
        var e = $.Event('change'); 
        $('#estado_civil').val('{{$personas->estado_civil}}').focus().trigger(e);

However, this function registers the display of the pre-selected value as a 'change' upon page load. Therefore, it triggers another function I made that notifies the user the value has changed.

Question: Is there a way to select/display the preselected value from the database, without registering it as a change?

Thank you so much!

Upvotes: 1

Views: 187

Answers (1)

Joel Kinzel
Joel Kinzel

Reputation: 970

I'm not super familiar with Laravel but from a quick read of the docs you'd do something like this in the blade:

<option value="1" {{estado_civil) == 1 ? "selected" : ""}}>Soltero(a)</option>
<option value="2" {{estado_civil) == 2 ? "selected" : ""}}>Unido(a)</option>

This uses a ternary to set the selected value of the input.

Upvotes: 1

Related Questions