2015-12-21 46 views
2

我只想在focus.how上選擇「請選擇」時,纔將css class dropdownliststyle添加到下拉菜單中嗎?如何使用jquery添加類到dropdownlist取決於選項

,這裏是我的jsfiddle鏈接https://jsfiddle.net/3dj3srxp/

CSS

.DropDownStyle { 
    background-color: red; 
    color: white; 
} 

jQuery的

$(document).ready(function() { 
    $('input[type="text"]').each(function() { 
     $(this).focus(function() { 
     $(this).addClass('textBoxStyle'); 
     }); 

     $(this).blur(function() { 
     $(this).removeClass('textBoxStyle'); 
     }); 
    }); 

    $('select').focus(function() { 
     $(this).addClass('DropDownStyle'); 
    }); 

    $('select').blur(function() { 
     $(this).removeClass('DropDownStyle'); 
     }); 

    }); 
+0

看到我更新的答案...它會更好地使用「更改」功能,並檢查值...我在我的答案更新你的小提琴。 – kevindeleon

回答

1

您需要添加一個if語句來檢查的值,它實際上會更好地使用更改功能:

$('select').change(function() { 
    if ($(this).val() == "select") { 
    $(this).addClass('DropDownStyle'); 
    } else { 
    $(this).removeClass('DropDownStyle'); 
    } 
}); 

你可以在這裏看到小提琴:https://jsfiddle.net/3dj3srxp/3/

0

重點僅適用於輸入要素,如果你想改變選擇框的顏色也許你會用「變」事件:

$('select').on('change',function() { 
    $(this).removeClass('DropDownStyle'); 

    if($(this).val() == 'select'){ 
    $(this).addClass('DropDownStyle'); 
    } 
}); 
+0

我無法讓你的工作。不知道爲什麼? – rampantNinja

+0

原因是在發佈我的答案後,kevindeleon改變了HTML中的某些內容。所以我不得不再次更新我的答案。如果您將此作爲驗證,我會建議您在用戶提交表單時檢查插入的值,並在出現錯誤時避免發佈表單。歡呼:) – Franco

2

讓我們一行完成。

$('select').on('change', function(){ 
    $(this).toggleClass('DropDownStyle', $(this).val() == 'select'); 
}); 
+0

希望我可以標記多個解決方案作爲答案。不同的方式做這件事。謝謝 – rampantNinja

相關問題