Onsubmit validate change background requried fields?

折月煮酒 提交于 2019-12-11 05:08:46

问题


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


回答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) {
        return false;
    }
}

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.




回答2:


Perhaps something like this:

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



回答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();
   }
  });
);


来源:https://stackoverflow.com/questions/6984480/onsubmit-validate-change-background-requried-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!