开发者

Change the class of a input field

Sorry. Let me rephrase:

I want js to change to class of a input field if it is left empty; Here is my code to detect a empty field:

function validateForm()
{
    var ctrl = document.forms[开发者_JAVA技巧"form1"]["username"];
    var x=ctrl.value;
    if (x==null || x=="") {
////////////CHANGE INPUT CLASS/////////////   
    }
    else {
    document.getElementById('username').style.backgroundColor="#FFFFFF";      
    }
}

i would have to css classes:

.inputfield {
background-color:white;
}

.inputfieldempty {
background-color:red;
}


To prevent submitting you need to call a function for the onsubmit event of the form (e.g. onsubmit="return checkFields()". In the function you will do the validations and return true or false depending on that. If the function will return false then the form will not be posted.

As part of your validations when you determine that a field's value is empty you can do the desired css changes as well. I don't know if you use vanilla javascript or a library such as jQuery in order to give more specific details.


Have a look at this tutorial for the excellent jQuery Validation plugin, which does exactly what you need and you don't even have to fiddle with cross-browser concerns.

If you don't want to use the plugin, I still recommend at least to use jQuery. Here's another tutorial that goes through all the necessary steps.


This post should take care of adding your CSS classes: Change an element's class with JavaScript

This post should take care of preventing forms to submit: https://developer.mozilla.org/en/DOM/event.preventDefault

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜