Skip to content Skip to sidebar Skip to footer

Onsubmit Validate Change Background Requried Fields?

Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class='required' ?

Solution 1:

Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:

document.getElementById("myForm").onsubmit = function() {
    var fields = this.getElementsByClassName("required"),
        sendForm = true;
    for(var i = 0; i < fields.length; i++) {
        if(!fields[i].value) {
            fields[i].style.backgroundColor = "#ff0000";
            sendForm = false;
        }
        else {
            //Else block added due to comments about returning colour to normal
            fields[i].style.backgroundColor = "#fff";
        }
    }
    if(!sendForm) {
        returnfalse;
    }
}

This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.

Here's a working example.

Solution 2:

Perhaps something like this:

$(document).ready(function () {
    $('form').submit(function () {
        $('input, textarea, select', this).foreach(function () {
            if ($(this).val() == '') {
                $(this).addClass('required');
            }
        });
    });
});

Solution 3:

I quickly became a fan of jQuery. The documentation is amazing.

http://docs.jquery.com/Downloading_jQuery

if You decide to give the library a try, then here is your code:

//on DOM ready event
$(document).ready(
  // register a 'submit' event for your form
  $("#formId").submit(function(event){
   // clear the required fields if this is the second time the user is submitting the form
   $('.required', this).removeClass("required");
   // snag every field of type 'input'.// filter them, keeping inputs with a '' value// add the class 'required' to the blank inputs.
   $('input', this).filter( function( index ){
       var keepMe = false;
       if(this.val() == ''){
         keepMe = true;
       }
       return keepMe;
     }).addClass("required");
   if($(".required", this).length > 0){
     event.preventDefault();
   }
  });
);

Post a Comment for "Onsubmit Validate Change Background Requried Fields?"