简体   繁体   中英

What's the easiest way to do form validation for jQuery?

All I want to do is to check if the textfield has been changed. If not, I want to highlight the boxes when submit is pressed. How do I do that? Seems very simple, but not sure why every other solution is so complicated.

Building upon Pim's answer, you can associate the changed flag for each text field using jQuery's data API.

// initially, assign changed to false for all text fields
$("input:text").data("changed", false);

// if any field changes, set its changed flag to true
$("input:text").change(function() {
    $(this).data("changed", true);
}

// finally on submission, get all text fields that did not
//  change by checking their "changed" property
var unchangedItems = $("input:text").filter(function() {
    return $(this).data("changed") === false;
});

您可以使用jQuery 验证插件。

Bassicly, you just say it has never been changed, and when it cahnges, you set a flag saying is has been changed:

var changed = false;
$('#textfield').change(function(){
    changed = true;
});
if(changed){
    $('.textbox').each(function(){
        $(this).addClass('.highlighted');
        //or something like this, whatever you want to do to highlight them
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM