2015-09-07 132 views
1

所以我正在一個窗體上工作。當您聚焦(單擊)文本字段時,該值將變爲空白。現在我想要默認值重新出現,如果用戶沒有填寫任何東西。輸入字段值重新填充如果焦點後空

因此,例如我有一個ID爲Question1的文本字段。這是明確的重點。

$(document).ready(function() { 
 

 
    $("#Question1").val('Naam *'); 
 
    $("#Question1").focus(function() { 
 
    $("#Question1").val(''); 
 
    }); 
 
    }); 
 
     

任何JavaScript的代碼?

編輯:由於CMS限制(concrete5),我無法使用佔位符。文本字段被生成。

+3

你爲什麼不使用佔位符的幫助? –

+0

使用placeholder =「something」,如果沒有寫在它上面,它會重新出現 –

+0

http://google.com/?q=jquery+placeholder+plugin – Andreas

回答

1

你可以做這樣的事情與blur()事件

$(document).ready(function() { 
 
    var temp = 'Naam *'; 
 
    $("#Question1").focus(function() { 
 
    if (temp == this.value) 
 
     // ------^-- empty the field only if the field value is initial 
 
     this.value = ''; 
 
     // emptying field value 
 
    }).blur(function() { 
 
    if (this.value.trim() == '') 
 
     // -----^-- condition field value is empty 
 
     this.value = temp; 
 
     // if empty then updating with initial value 
 
    }).val(temp); 
 
    //----^-- setting initial value 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="text" id="Question1" />

+0

這可以工作,但是一旦你輸入了某些東西,並且你點擊了文本字段:文本字段變爲空白+不能刪除填入的內容。 – Jacob

+0

@JacobVanAchter:已更新 –

+0

非常好,正是我的意思,謝謝! – Jacob