Javascript 如何根据输入文本更改类名
我需要根据文本值更改输入的类。当值为空时,它应该是默认值,当有值时,它应该将类更改为inputtextJavascript 如何根据输入文本更改类名,javascript,html,Javascript,Html,我需要根据文本值更改输入的类。当值为空时,它应该是默认值,当有值时,它应该将类更改为inputtext 请尝试以下代码: <style> .inputnotext{ background:#ddd; } .inputtext{ background:transparent } /* when their is text */ </style> <form> <
请尝试以下代码:
<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>
希望它能帮助您:-尝试以下代码:
<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>
希望它能帮助您:-这是一个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);
}
}
这是一个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);
}
}
您可以使用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");
}
您可以使用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");
}
到目前为止你试过什么?堆栈溢出是为了帮助修复错误和问题,而不是为您编写代码。您是否使用jQuery或任何其他库?到目前为止您尝试了什么?堆栈溢出用于帮助修复错误和问题,而不是为您编写代码。是否使用jQuery或任何其他库?检查输入值不需要整个库。检查输入值不需要整个库。