获取空输入的正确标签 [英] Get the correct label of an empty input

查看:68
本文介绍了获取空输入的正确标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友

我的表格如下;

<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的具有空值的输入标签识别并添加一个名为错误"的类.

When I submit the form, I want to identify and add a class called 'error' for only the labels of inputs which having empty values using jQuery.

请帮助我简化这个问题.

Please help me short this problem.

感谢和问候, 鲁申.

推荐答案

.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)
})

这篇关于获取空输入的正确标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆