Adrian
Adrian

Reputation: 3052

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

Upvotes: 4

Views: 2346

Answers (2)

Nitesh Gupta
Nitesh Gupta

Reputation: 108

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>

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115202

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

Upvotes: 2

Related Questions