簡體   English   中英

如果輸入類型不為空,則添加CSS樣式

[英]if input type not empty add a css style

我想直接在加載頁面上檢查輸入文本,但不在輸入中添加任何內容,則他不起作用。 如何解決?

<form action="">
  <input type="text" id="author" value="Bill">
</form>

$("#author").keyup(function(){
    if($(this).val()) {
        $("#author").addClass("notempty");
        /* if input is not empty do background yellow */
    } else {
        $("#author").addClass("empty");
         /* else background is red */
    }
});

演示http://jsfiddle.net/540dwmcn/

您的代碼設置為在keyup事件上觸發。 要在頁面加載時也運行它,請通過添加.keyup();手動觸發.keyup(); 最后。

jsFiddle示例

另外,您可能還想清除這些類(注意在提琴中使用.removeClass()

$("#author").keyup(function () {
    if ($(this).val()) {
        $("#author").removeClass().addClass("notempty");
        /* if input is not empty do background yellow */
    } else {
        $("#author").removeClass().addClass("empty");
        /* else background is red */
    }
}).keyup();

演示

$("#author").keyup(function(){
    if($(this).val()) {
        $("#author").addClass("notempty")
        .removeClass("empty");
        /* if input is not empty do background yellow */
    } else {
        $("#author").addClass("empty")
        .removeClass("notempty");
        /* else background is red */
    }
}).keyup();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM