2011-11-29 51 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