Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda