コンボボックス(SELECT)要素の変更イベントをキャンセルする方法。HTMLSELECT要素のonbeforeまたはonchangingイベントはありません。私が置く場合:
<SELECT onchange="return false;">
<OPTION value=a>A</OPTION>
<OPTION value=b>B</OPTION>
</SELECT>
イベントはキャンセルされません。
コンボボックス(SELECT)要素の変更イベントをキャンセルする方法。HTMLSELECT要素のonbeforeまたはonchangingイベントはありません。私が置く場合:
<SELECT onchange="return false;">
<OPTION value=a>A</OPTION>
<OPTION value=b>B</OPTION>
</SELECT>
イベントはキャンセルされません。
<select>
元の値をどこかに保存する必要があります。値を元に戻すことができるようにします。
イベントをキャンセルすると、それだけが行われます。イベントをキャンセルするだけで、値は変更されません。
例(jQueryを使用):
$(function(){
$('select').each(function(){
$(this).data('selected', $(this).val()); // back up value
}).change(function(){
if(confirm('Are you sure you want to change the element?')){
$(this).data('selected', $(this).val()); // back up new value
}
else{
$(this).val($(this).data('selected')); // restore old value
}
});
});
デモ:http://jsfiddle.net/pL2B4/
純粋なJavaScriptソリューション(jQueryなし):
var select = document.getElementsByTagName('select');
for (var i = 0, len = select.length; i < len; i++) {
var el = select[i];
el.setAttribute('data-selected', el.value);
el.addEventListener('change', function() {
if (confirm('Are you sure you want to change the element?')) {
el.setAttribute('data-selected', el.value);
}
else {
el.value = el.getAttribute('data-selected');
}
});
}
デモ:http://jsfiddle.net/pL2B4/1/