遍历多种类型的输入

mpdc

我正在尝试在jQuery中编写一些表单验证。这很基本,我只检查空输入。

不过,也有三种不同类型的窗体上的元素:<input type="text"><select><input type="checkbox">我很难让我的验证与所有这些一起使用。

到目前为止,这是我的代码:

部分HTML

<input type="hidden" name="required" value="title,first_name,family_name,job_title,company_name,country,address_1,town_city,post_code,telephone_2,email,subprimary_activity,subjob_title2,subscription" />

JAVASCRIPT

$("input[name=submit_form]").on("click", function(e) {
    e.preventDefault();
    var missing_items = [];
    var required_array = $("input[name=required]").val().split(",");
    var i;
    for (i = 0; i < required_array.length; i++) {
        var input_name = required_array[i];
        if ($("input[name=" + input_name + "]").val() == "" || $("select[name=" + input_name + "]").val() == "" || !$("input[name=" + input_name + "]").is(":checked")) {
            missing_items.push(input_name);
        }
    }
    alert(missing_items);
});

alert()目前通知我的每一个元素,无论它是不是缺少值/检查。我知道这是为什么-这是因为我if有三个参数,并且由于不能是<input> and和a <select>,所以它将始终为true。

我该如何重写它才能正常运行?有没有一种方法可以检查元素是什么类型的输入,或者是否存在特定元素,因此仅运行相关的验证?

例如

if (is input text) {
    check val() ! empty
}
else if (is select) {
    check val() !empty
}
else if (is input checkbox) {
    check :checked
}
穆罕默德·谢维尔KP

在这里更改代码

if ($("input[name=" + input_name + "]").val() == "" || $("select[name=" + input_name + "]").val() == "" || !$("input[name=" + input_name + "]").is(":checked")) {
            missing_items.push(input_name);
        }

对此

var element = $("[name=" + input_name + "]");
if(element.is(":text"))
  // your code
else if (element.is("select")
  // your code
else if (element.is(":checkbox")
  // your code

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章