jQuery-对表单中的每个字段执行操作

jQuery - Make action on each field in form

本文关键字:字段 执行 操作 表单 jQuery-      更新时间:2023-09-26

我想在jQuery 上制作一个简单的表单验证器

$('#clients_name').keyup(function(){
    if($('#clients_name').val().length >= 2){
      (...)
    }
});

但我想检查更多的输入(文本,选择…),我不知道我应该如何更改第一行,以便对我表单中的任何输入进行通用操作"keyup"(或其他什么)。这对input=text很好,但对select not。。。

$('input[type=text],select').keyup(function(){
    if($('#clients_name').val().length >= 2){
      (...)
    }
    if($('#clients_street').val().length >= 2){
      (...)
    }
});

只需使用This

$('input[type="text"]').keyup(function(){   // $('select,input[type="checkbox"]').on('change',function(){
    if ($(this).val().length >= 2) {
      (...)
    }
    //Or can be
    if (this.value.length >= 2) {
      (...)
    }
});

.keyup仅适用于文本框。您需要使用.on('change',function(){..})来选择框和复选框,单选。

传递给.keyup()的回调函数中this的上下文将设置为当前DOM元素。简单参考this。但是select元素不会触发keyup事件。所以我会把你在那里的东西改成:

$('input[type=text], select').on("change", function(){
    if(this.value.length >= 2){
      // do your validation
    }
});