Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
How to select input value from onchange using jQuery?

I have a select and input tags. I am updating a value of a text input based from what is selected in the select tag.

Select Tag

<select class="form-control form-field-username form-field-users">
<option class="form-field-first-option" value="0" selected="selected">Select User...</option>
<option value="1">Peter Fel</option> 
<option value="2">Mark Getty</option>
</select>

Input Tag

<input name="user_id" id="user_id" class="form-control form-field-user-id" type="number">

Code for onchange select:

$('.form-field-username').change( function() {
    $(this).find(":selected").each(function () {
        var userId = $(this).val();

        $('.form-field-user-id').val(userId);

    });

});

I want to set the value of text input with user id of "user_id" to null or undefined if the onchange chooses the first value or user_id == 0.

Do you know how to modify the code? Any help is appreciated. Thanks

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Check the value within the handler using a ternary operator. The each() method is completely unnecessary here since there is only single selected option.

$('.form-field-username').change(function() {
  $('.form-field-user-id').val(this.value == 0 ? '' : this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control form-field-username form-field-users">
<option class="form-field-first-option" value="0" selected="selected">Select User...</option>
<option value="1">Peter Fel</option> 
<option value="2">Mark Getty</option>
</select> 
<input name="user_id" id="user_id" class="form-control form-field-user-id" type="number">

about 4 years ago · Santiago Trujillo Denunciar

0

Set empty on first option value.

<select class="form-control form-field-username form-field-users">
  <option class="form-field-first-option" value="" selected="selected">Select User...</option>
  <option value="1">Peter Fel</option> 
  <option value="2">Mark Getty</option>
</select>
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda