0

I have a little procedure to prevent server side action if all texboxes do not have values. I want to assign a color to the texbox for in case a value was not added.

This is not working the way I expected.

var txtName = document.getElementById("MainContent_txtName").value;
var txtSurname = document.getElementById("MainContent_txtSurname").value;
var txtContact = document.getElementById("MainContent_txtContactNumber").value;
var txtEmail = document.getElementById("MainContent_txtEmail").value;
var txtMessage = document.getElementById("MainContent_txtMessage").value;

var fields = new Array(txtName, txtSurname, txtContact, txtEmail, txtMessage);
var tot = 0;
for (var i = 0; i < fields.length; i++) {

    if (fields[i] == "") {
        fields[i].style.backgroundcolor = '#FEF5CA';
        tot++;
    }
    else {
        fields[i].style.backgroundcolor = "white";
    }

}
if (tot > 0) {
    return false;
}
return true;

regards

4

2 回答 2

5

The problem is you are creating an array of values, you need the elements themselves:

var txtName = document.getElementById("MainContent_txtName");
var txtSurname = document.getElementById("MainContent_txtSurname");
var txtContact = document.getElementById("MainContent_txtContactNumber");
var txtEmail = document.getElementById("MainContent_txtEmail");
var txtMessage = document.getElementById("MainContent_txtMessage");

var fields = [txtName, txtSurname, txtContact, txtEmail, txtMessage];
var tot = 0;
for (var i = 0; i < fields.length; i++) {

    if (fields[i].value == "") {
        fields[i].style.backgroundColor = '#FEF5CA';
        tot++;
    }
    else {
        fields[i].style.backgroundColor = "white";
    }

}
if (tot > 0) {
    return false;
}
return true;

You have to change backgroundcolor to backgroundColor and add .value to your if check.

于 2013-07-09T14:57:16.097 回答
2

try style.backgroundColor instead of style.backgroundcolor (note the capital "C") Javascript is case sensitive.

于 2013-07-09T14:57:05.987 回答