2011-11-29 106 views
0

我需要根據文本值更改輸入class。當value爲空時,它應該是默認值,當有value時,它應該將類更改爲inputtext如何根據輸入文字更改班級名稱

<style> 
    .inputnotext{ background:#ddd; } 
    .inputtext{ background:transparent } /* when their is text */ 
</style> 

<form> 
    <input class="inputnotext" type="text" name="firstname" /><br /> 
    <input class="inputnotext" type="text" name="lastname" /> 
</form> 

<script> 
    /* script to write ??? */ 
</script> 
+3

你到目前爲止嘗試過什麼?堆棧溢出是爲了幫助修復錯誤和問題,而不是爲您編寫代碼。 –

+0

你使用jQuery或任何其他庫嗎? – Variant

回答

2

這是一個JavaScript,您可以使用:

var input = document.getElementsByTagName('input'); 

keyupHandler = function(input){ 
    if (input.value.length){ 
     input.setAttribute('class', 'inputnotext'); 
    } 
    else { 
     input.setAttribute('class', ''); 
    } 
} 

for (i=0; i<input.length; i++){ 
    input[i].onkeyup = function(){ 
     keyupHandler(this); 
    } 
    input[i].onchange = function(){ 
     keyupHandler(this); 
    } 
} 

jsFiddle example

+0

完美地起作用... – alex

1

試試下面的代碼:

<style> 
     .inputnotext{ background:#ddd; } 
     .inputtext{ background:transparent } /* when their is text */ 
     </style> 

     <form> 
     <input class="inputnotext" type="text" name="firstname" onblur="checkValue(this);"/><br /> 
     <input class="inputnotext" type="text" name="lastname" onblur="checkValue(this);"/> 
     </form> 

     <script> 
     function checkValue(c){ 
      var val = c.value; 
    var id = c.id; 
    if(val.length > 0){ 
    document.getElementById(id).className += "inputtext"; 
    }else{ 
document.getElementById(id).className += "inputnotext"; 

} 
      } 
     </script> 

希望它可以幫助你:-)

0

你可以做一些事情像這樣使用jQuery:

$(document).ready($(input:text[name=firstname]).change(function() { 
    var val = $(input:text[name=firstname]).val() 
    if(val!="") 
    { 
    $(input:text[name=firstname]).removeClass("inputnotext").addClass("inputtext"); 
    } 
+0

您不需要整個庫來檢查輸入的值。 – Teneff