Set an attribute of the database to an input

0

I have a test function in javascript and what it does is that when I select a developer in the select, I pass the name of this to an input, but it passes me the id (all the select fields are from the database) Could you help solve it? I just need the developer's name in the input

<script>
 function prueba(x) 
 {

    var opcion=document.getElementById('inputdesa').value=x;
 }
 </script>



<div class="form-group">
<label for="">Desarrollador</label>
    <select name="id_calcu" id="inputid_calcu" class="form-control" onchange="prueba(this.value);">

   @foreach($desarrollos as $desarrollo)
     <option value="{{ $desarrollo['id_calcu'] }}">{{ $desarrollo['desarrollador'] }}</option>
   @endforeach

    </select>
</div>

    
asked by DANIEL FELIPE LOPEZ VARGAS 30.10.2017 в 16:01
source

3 answers

2

This happens because the .value captures the value that is in the value attribute of your selected option to which you are assigning $desarrollo['id_calcu'] .

To capture the text of the selected option you must do the following:

function prueba(x){
    var indice = x.selectedIndex;
    var texto = x.options[indice].text;
    var opcion = document.getElementById('inputdesa').value = texto;
}
<select onchange="prueba(this);">
    <option value="1">Opción 1</option>
    <option value="2">Opción 2</option>
    <option value="3">Opción 3</option>
</select>

<input type="text" id="inputdesa">
    
answered by 30.10.2017 / 16:18
source
2

Look carefully when you compose the option . In value you put the id, and in the visible content the name of developer, you are getting the id with your JS because you retrieve the content with value .

You need to use innerHTML .

Example:

<select>
    <option value="opciones" selected>Elige una opción</option>
    <option id="Uno" value="1">Uno</option>
    <option id="Dos" value="2">Dos</option>
</select>

<script type="text/javascript">

    /**
     * Opción 1
     * Requiere que le añadas una "id" a cada "option" para recuperar su contenido
     *
     */
    var selected_option = document.getElementById( 'Uno' ).innerHTML;
    console.log( selected_option );
</script>
    
answered by 30.10.2017 в 16:26
1

You have to get the index of the selected option using the property selectedIndex of select and then based on the index you access property select of the array options of select asi:

function mostrarDesarrollador()
{
  var select = document.getElementById("desarrolladores");
  document.getElementById("desarrollador").value = select.options[select.selectedIndex].text;
}
<select onchange="mostrarDesarrollador()" id="desarrolladores">
  <option value="1">Einer</option>
  <option value="2">Einer 2</option>
  <option value="3">Einer 3</option>
</select>

<input type="text" id="desarrollador" />
    
answered by 30.10.2017 в 16:19