Fill in textfield with the description corresponding to the selected value in a combobox

1

I have in my view a select that receives the data of the functions and the lists.

<select id="id_mfuncao" name="id_mfuncao" class="form-control">
    <option value=""><< selecione >></option>
    @foreach($mfuncoes as $mfuncao)
        <option value="{{ $mfuncao->id }}">{{ $mfuncao->nome }}</option>
    @endforeach
</select>

Apart from the id and the name, I also get the description of the functions. How can I do to load the description of the selected function in a textfield?

<input readonly="" type="text" id="descricao" name="descricao" class="form-control">

I do not think I need to use ajax to fetch the value again since I already have it loaded, but I lack knowledge and I did not get a term to search for a solution on the web.

These are the data I get from the function:

Whenselected"General Officer ..." I want to show the description in textfield.

    
asked by anonymous 15.01.2016 / 13:47

1 answer

2

Assign the description in your options

Since you are already using the value and text of the option, you can create an additional attribute in option . See data- *

@foreach($mfuncoes as $mfuncao)
    <option value="{{ $mfuncao->id }}" data-descricao="{{ $mfuncao->descricao}}">
        {{ $mfuncao->nome }}
    </option>
@endforeach

Assign the selected value to the input

Add the event on change to select and get the value of option selected or text and assign input .

  • .val() gets the value of the selected option
  • $("option:selected", this).text() gets selected option text
  • $("option:selected", this).data('descricao') gets the value of the named date attribute of description

See in practice:

$('body').on('change', '#mySelect', function() {
  $('#txtValue').val($(this).val());
  $('#txtText').val($("option:selected", this).text());
  $('#txtData').val($("option:selected", this).data('descricao'))
});

$('#mySelect').trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="mySelect">
  <option value="1" data-descricao="Descrição 1">Valor 1</option>
  <option value="2" data-descricao="Descrição 2">Valor 2</option>
</select>
<p>Value:<input readonly="" type="text" id="txtValue"></p>
<p>Text:<input readonly="" type="text" id="txtText"></p>
<p>Data:<input readonly="" type="text" id="txtData"></p>
    
15.01.2016 / 14:03