Get the value of a select option with JQuery?

1

What happens is the following I have this select

<select required="required" class="form-control" name="servicio">
   <option value="" selected="selected"></option>
   <option value="1">HelpDesk</option>
   <option value="1">HelpDesk2</option>
</select>
<input id="servicioSelecionado" name="nom_Servicio" type="hidden" value="prueba">

What I need is:

the value is the one between the option <option>Valor</option> in this case HelpDesk or Heldesk2.

When the user selects an option, the value that I need must be stored in the value of the hidden . In the event that the user later changes his mind and selects another option, the hidden should be updated with the new data so that when the form is sent, the variable is updated with the option that the user has. Selected

That is, the only thing I need is to have the hidden updated with the moment the form is sent.

    
asked by FuriosoJack 30.03.2017 в 17:41
source

1 answer

4

Listening to the Change () event and then accessing the text of option selected by text () (I modified the type text the input to show the result)

$(document).on('change', '#servicio', function(event) {
     $('#servicioSelecionado').val($("#servicio option:selected").text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select required="required" class="form-control" name="servicio" id="servicio">
<option value="" selected="selected"></option>
<option value="1">HelpDesk</option>
<option value="2">HelpDesk2</option>
</select>
<br>
<br>
<input id="servicioSelecionado" name="nom_Servicio" >
    
answered by 30.03.2017 / 17:54
source