2017-03-09 45 views
4

我有一個選擇和輸入標籤。我正在更新基於select標籤中選定內容的文本輸入的值。如何使用jQuery從onchange選擇輸入值?

選擇標記

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

代碼的onchange選擇:

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

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

    }); 

}); 

我想用 「USER_ID」 的用戶ID設置文本輸入的值如果onchange選擇第一個值或user_id == 0,則爲null或undefined。

你知道如何修改代碼嗎?任何幫助表示讚賞。謝謝

回答

2

使用ternary operator檢查處理程序中的值。因爲只有一個選擇的選項,所以這裏完全不需要each()方法。

$('.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">

+1

謝謝!奇蹟般有效。你很棒! –

+0

我只是有一個問題。你的代碼如何在沒有我的$(this).find(「:selected」)的情況下找到「:selected」的值,each(function(){}); ?? –

+0

yes,'$(this).val()'或'this.value'保存所選值 –

1

設置在第一個選項值空。

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

謝謝Nitesh! –