2013-06-20 42 views

回答

23

DEMO-->http://jsfiddle.net/2Xgfr/829/

HTML

<input type="text" id="subEmail" onchange="checkFilled();"> 

的JavaScript

function checkFilled() { 
    var inputVal = document.getElementById("subEmail"); 
    if (inputVal.value == "") { 
     inputVal.style.backgroundColor = "yellow"; 
    } 
    else{ 
     inputVal.style.backgroundColor = ""; 
    } 
} 

checkFilled(); 

注:你正在檢查值並將顏色設置爲不允許的值,這就是爲什麼它會給你提供錯誤。嘗試像上面那樣。

+0

如果在文本框中存在某些東西,該如何去除顏色? – samyb8

+0

@ samyb8更新的小提琴... –

+0

爲什麼它沒有工作,而不是有getElementsById我把getElementsByClassName和更改ID在HTML中的類? – samyb8

2

風格不添加到輸入的值,因此使用像

function checkFilled() { 
    var inputElem = document.getElementById("subEmail"); 
    if (inputElem.value == "") { 
     inputElem.style.backgroundColor = "yellow"; 
       } 
     } 
4

你沒有調用函數,你有其他錯誤,應該是:

function checkFilled() { 
    var inputVal = document.getElementById("subEmail"); 
    if (inputVal.value == "") { 
     inputVal.style.backgroundColor = "yellow"; 
    } 
} 
checkFilled(); 

Fiddle

您將inputVal設置爲輸入的字符串值,但您嘗試設置style.backgroundColor,它不會工作,因爲它是一個字符串,而不是元素。我改變了你的變量來存儲元素對象而不是它的值。

4

對身體標記的onload嘗試設置它像

document.getElementById("subEmail").style.backgroundColor = "yellow"; 

,之後該輸入域檢查的變化,如果某個值是存在的,或者它漆成黃色的像

function checkFilled() { 
var inputVal = document.getElementById("subEmail"); 
if (inputVal.value == "") { 
    inputVal.style.backgroundColor = "yellow"; 
      } 
    } 
3

試試這個:

function checkFilled() { 
var inputVal = document.getElementById("subEmail"); 
if (inputVal == "") { 
    inputVal.style.backgroundColor = "yellow"; 
    } 
} 
2
<! DOCTYPE html> 
<html> 
<head></head> 
<body> 

    <input type="text" id="subEmail"> 


    <script type="text/javascript"> 

     window.onload = function(){ 

     var subEmail = document.getElementById("subEmail"); 

     subEmail.onchange = function(){ 

      if(subEmail.value == "") 
      { 
       subEmail.style.backgroundColor = "red"; 
      } 
      else 
      { 
       subEmail.style.backgroundColor = "yellow"; 
      } 
     }; 

    }; 



    </script> 

</body> 

0

您可以使用javascript和css來設計它。將樣式添加到CSS,並使用classlist屬性使用javascript添加/刪除樣式。這是一個JSFiddle它。

<div class="div-image-text"> 
    <input class="input-image-url" type="text" placeholder="Add text" name="input-image"> 
    <input type="button" onclick="addRemoteImage(event);" value="Submit"> 
    </div> 
    <div class="no-image-url-error" name="input-image-error">Textbox empty</div> 

addRemoteImage = function(event) { 
    var textbox = document.querySelector("input[name='input-image']"), 
    imageUrl = textbox.value, 
    errorDiv = document.querySelector("div[name='input-image-error']"); 
    if (imageUrl == "") { 
    errorDiv.style.display = "block"; 
    textbox.classList.add('text-error'); 
    setTimeout(function() { 
     errorDiv.style.removeProperty('display'); 
     textbox.classList.remove('text-error'); 
    }, 3000); 
    } else { 
    textbox.classList.remove('text-error'); 
    } 
}