2016-07-07 91 views
0

我做了一些jquery驗證,並且當用戶離開input並且沒有寫入內容時,我想要一些文本顯示爲placeholder佔位符沒有顯示

我寫了這個代碼

$('input[type="text"]').on('blur', function() { 
    if (!!$(this).val()) { 
     $(this).css({ 
      'border': '#ff8383 1px solid' 
     }); 
     $(this).attr('placeholder', 'this field is required'); 
    } 
    else { 
     $(this).css({ 
      'border': '#c3c3c3 1px solid' 
     }); 
     $(this).attr('placeholder', ''); 
    } 
}); 

它可以在Chrome瀏覽器開發工具 chrome dev tool,但它不`噸顯示在頁面上。

回答

1

你有一個額外!這裏:

!!$(this).val() 

,您可以在同一(this)

$('input[type="text"]').on('blur', function() { 
 
    if (!$(this).val()) { 
 
    $(this).css({ 
 
     'border': '#ff8383 1px solid' 
 
    }).attr('placeholder', 'this field is required'); 
 
    } else { 
 
    $(this).css({ 
 
     'border': '#c3c3c3 1px solid' 
 
    }).attr('placeholder', ''); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="text" placeholder="test" /> 
 
<input type="text" placeholder="" /> 
 
<input type="text" />

+0

加入cssattr起初,我寫了一個「! 「,但是如果聲明不起作用。這是因爲我的價值=「」在我的HTML。你給了我一個線索。 –

+0

我現在更新了答案,如果你想看看 – dippas

1

這可能是問題; if語句中有2個爆炸聲。

if (!!$(this).val()) {