4

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

2 Answers 2

2

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">

Sign up to request clarification or add additional context in comments.

2 Comments

I just have a question. How was your code able to find out the value of ":selected" without my $(this).find(":selected").each(function () {}); ??
yes, $(this).val() or this.value holds the selected value
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.