How to select input value from onchange using jQuery?

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

Choose 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 exchange:

$('.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 text input value with user id "user_id" to null or undefined if onchange selects the first value or user_id == 0.

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

+4
source share
2 answers

Check the value inside the handler using the ternary operator . The method each()is completely unnecessary here, since there is only one option chosen.

$('.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">
Hide result
+2

.

<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>
+1

Source: https://habr.com/ru/post/1671853/


All Articles