如何在onchange之前从下拉列表中获取先前选定的值

Siv*_*esh 8 javascript jquery javascript-events

我知道这是最简单的问题,但无法得到正确的答案

<div class="col-12 col-md-4 col-lg-5 mt10-xs">
     <p>Status</p>
     <div class="form-group FL mr20 w100-xs">
           <div class="rsi-custom-select">
                 <select class="form-control" id="statustab_{{ $row['placementkey'] }}" class="select2-selecting" onchange="listingByStatus(this,'{{ $row['placementkey'] }}')">
                     @foreach($placementStatus as $pl)
                        <option @if($pl['placement_status_id'] ==  $row['statusid'] ) selected @endif value="{{$pl['placement_status_key']}}">{{$pl['placement_status']}}</option>
                     @endforeach
                 </select>
            </div>
      </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是我的onchange功能.在此如何从我的选择框中获取先前的选定值

function listingByStatus(ths,key){
      var thisSelect = $('#statustab_'+key).text();
      var statusText = $( "#statustab_"+key+" option:selected" ).text();
      var currentval = $( "#statustab_"+key+" option:selected" ).val();
}
Run Code Online (Sandbox Code Playgroud)

Sap*_*aik 8

使用data()元素获得焦点时保存原始值:

$('.select2-selecting').on('focusin', function(){
    console.log("Saving value " + $(this).val());
    $(this).data('val', $(this).val());
});
Run Code Online (Sandbox Code Playgroud)

然后在onchange函数中获取保存的旧值:

function listingByStatus(ths,key){
         var thisSelect = $('#statustab_'+key).text();
         var statusText = $( "#statustab_"+key+" option:selected" ).text();
         var currentval = $( "#statustab_"+key+" option:selected" ).val();
         var prev = $('.select2-selecting').data('val'); //old value
         console.log("Old value " + prev);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以在页面上包含隐藏的输入字段

<input type="hidden" id="previous_value" name"previous_value" value="abc"/>
Run Code Online (Sandbox Code Playgroud)

然后在您的脚本中,您可以访问任何其他输入:

var previous = $('#previous_value').val();
Run Code Online (Sandbox Code Playgroud)

在发生onchange事件后设置它:

$('#statustab_{{ $row['placementkey'] }}').addEventListener('change', function (e) {
    $('$previous_value').val(e.value)
}) 
Run Code Online (Sandbox Code Playgroud)