2015-05-29 117 views
3

如果選擇字段已更改,我想進行jQuery檢查。如果更改,則設置警報消息(已更改),如果返回到默認值,則設置另一個警報消息(默認值)。jQuery檢查是否選擇字段已更改

$('select').on('change',function() { 
    var isDirty = false; 

    $('select').each(function() { 
     var $e = $(this);  
     if (!$e[0].options[$e[0].selectedIndex].defaultSelected) { 
     isDirty = true; 
     }  
    }); 

    if(isDirty == true) { 
     alert("has changed"); 
    } else { 
     alert("default value");   
    } 
}); 

請指教,如果這是正確的方法。

回答

4

你不需要內部each循環。另外$(this)[0]可以優化只是this

$('select').on('change', function() { 
 
     
 
    var isDirty = !this.options[this.selectedIndex].defaultSelected; 
 

 
    if (isDirty) { 
 
     alert("has changed"); 
 
    } else { 
 
     alert("default value"); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select name="" id=""> 
 
    <option value="1">Label 1</option> 
 
    <option value="2" selected>Label 2</option> 
 
    <option value="3">Label 3</option> 
 
    <option value="4">Label 4</option> 
 
</select>

+0

謝謝您的明確的答案。關於'each'循環,如果我想檢查表單中所有可用的選擇字段,它不會被需要?這是一個新手問題:) –

+0

'$('select')。on('change',...)'已經處理所有的選擇框(它在內部使用)。 – dfsq

1

我會做這樣的事情:

HTML:

<select data-default="one" id="the-select"> 
    <option>one</option> 
    <option>two</option> 
</select> 

的Javascript:

$('#the-select').change(function() { 
    var changed = $(this).val() != $(this).data('default'); 
    alert(changed ? 'changed' : 'not changed'); 
});