Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 获取空输入的正确标签_Jquery_Validation_Input_Label - Fatal编程技术网

Jquery 获取空输入的正确标签

Jquery 获取空输入的正确标签,jquery,validation,input,label,Jquery,Validation,Input,Label,朋友们 我有一个表格如下 <form method="post" id="contact_form" action=""> <label for="name">Name</label> <input type="text" name="name" id="name" /> <label for="email">Email</label> <input type="text" name="email" id="ema

朋友们

我有一个表格如下

<form method="post" id="contact_form" action="">
<label for="name">Name</label>
<input type="text" name="name"  id="name" />

<label for="email">Email</label>
<input type="text" name="email" id="email" />

<label for="purpose">Purpose</label>
<input type="text" name="purpose" id="purpose"  />                              

    <input type="submit" value="Submit"/> 
</form> 

名称
电子邮件
目的
当我提交表单时,我想使用jQuery为具有空值的输入标签标识并添加一个名为“error”的类

请帮我解决这个问题

感谢和问候, 鲁森

试试这个:

$('#contact_form').submit(function() {
    $(this).find("input:text").each(function() {
        if ($.trim($(this).val()) == '') {
            $(this).css({ border: "2px red solid" });
            return false;
        }
    })
});

?如果您提交表单,页面将被删除并替换为表单提交的结果(除非您通过ajax提交表单,并且代码未显示给我们)。如果您能提供一个更完整的问题解释,以及您是如何试图解决它的,我们可能会提供帮助。非常感谢您,这一切正常。但我不明白它的工作原理。我是jQuery的新手,如果您能给我解释一下,我将不胜感激。
.homework {
   color: red;
}
$('#contact_form').submit(function(){ // listen to the submit event
    var err = 0;  // define a varible with initial value of 0
    $('input[type=text]', this).each(function(){ // iterate through the text inputs
       var val = $.trim(this.value); // trim and store the value
       // if the value is empty add a class to the previous label otherwise remove it(is it has)
       $(this).prev().toggleClass('homework', !val ); 
       if (!val) err++; // if the value is empty add 1 to the err variable  
    })
    return !err; // return false if there is one or more empty field(s)
})
$('#contact_form').submit(function() {
    $(this).find("input:text").each(function() {
        if ($.trim($(this).val()) == '') {
            $(this).css({ border: "2px red solid" });
            return false;
        }
    })
});