javascript – 检查输入字段的值并添加一个类

前端之家收集整理的这篇文章主要介绍了javascript – 检查输入字段的值并添加一个类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个输入字段和一个提交按钮(内联显示).输入字段填写完毕后,我尝试向下一个同级添加一个类.所以如果填写名字输入字段,请在电子邮件输入字段中添加一个类,如果电子邮件输入字段已填写,则将类添加到下一个输入字段等等…

这是我的代码到目前为止

$('.form-display #mce-FNAME').blur(function() {
     if($.trim(this.value).length) {
        $('#mce-EMAIL').toggleClass('animated pulse');
     }else if(...){ }...
});

我的HTML看起来像这样:

<div class="form-display">
    <div class="mc-field-group">
        <label for="mce-FNAME">First Name </label>
        <input type="text" value="" name="FNAME" class="" id="mce-FNAME">
    </div>
    <div class="mc-field-group">
        <label for="mce-EMAIL">Email Address </label>
        <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
    </div>
    <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">
</div>

解决方法

将除提交按钮之外的所有输入都收集到集合中.

在输入时,根据当前输入是否具有值来切换下一个输入的类:

var inputs = $('.form-display input').not(':submit');

inputs.on('input',function() {
  $(inputs[inputs.index(this) + 1]).toggleClass('animated pulse',this.value > '');
});

Fiddle

片段:

var inputs = $('.form-display input').not(':submit');  //all inputs except submit button

inputs.on('input',this.value > '');
});
.animated.pulse {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-display">
  <div class="mc-field-group">
    <label for="mce-FNAME">First Name </label>
    <input type="text" value="" name="FNAME" class="" id="mce-FNAME">
  </div>
  <div class="mc-field-group">
    <label for="mce-EMAIL">Email Address </label>
    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
  </div>
  <div class="mc-field-group">
    <label for="mce-CITY">City </label>
    <input type="text" value="" name="EMAIL" class="required email" id="mce-EMAIL">
  </div>
  <div class="mc-field-group">
    <label for="mce-STATE">State </label>
    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
  </div>
  <div class="mc-field-group">
    <label for="mce-ZIP">Zip </label>
    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
  </div>
  <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">
</div>

猜你在找的JavaScript相关文章