2016-10-10 15 views
0

私は選択フィールドを持っており、選択フィールドのオプションを変更すると確認メッセージが表示されます。私の問題は、確認メッセージを取り消した後、selectオプションフィールドの値を変更することをどうやって防ぐのかです。jqueryを使用してキャンセルした後に選択オプションを変更しないようにする方法は?

$('.changeScoreFem').on('change', function(){ 
    if (confirm('Are you sure to change this score?')) { 
     //continue to change the value 
    } else { 
     //else do not change the selecoption field value 
    } 
}); 
+2

から[の可能な複製を選択したアイテムを渡す場合には、ページの読み込みにトリガされます後jQueryはselectの変更を防ぐ](http://stackoverflow.com/questions/5426387/jquery-prevent-change-for-select) – Dekel

答えて

2

必要に応じて、それを元に戻す、選択の現在の値を格納することによってこれを行うことができます。

データを格納するカスタムイベントを使用し、そのカスタムイベントはまた、あなたがサーバー

var $sel = $('.changeScoreFem').on('change', function(){ 
    if (confirm('Are you sure to change this score?')) { 
     // store new value   
     $sel.trigger('update'); 
    } else { 
     // reset 
     $sel.val($sel.data('currVal'));   
    } 
}).on('update', function(){ 
    $(this).data('currVal', $(this).val()); 
}).trigger('update'); 

DEMO

2

選択したオプションを変数に保存する必要があります。キャンセルされた場合は、選択し直してください。

var selected = $(".changeScoreFem option:selected"); 
 
$(".changeScoreFem").on("change", function(e){ 
 
    if (confirm("Are you sure to change this score?")) 
 
     selected = $(this).find("option:selected"); 
 
    else 
 
     selected.prop("selected", true); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select class="changeScoreFem"> 
 
    <option>Option 1</option> 
 
    <option>Option 2</option> 
 
    <option>Option 3</option> 
 
</select>

関連する問題