Codehan25 Codehan25 - 5 months ago 28
jQuery Question

Check value of input field and add a class

I have two input fields and a submit button (displayed inline). I'm trying to add a class to the next sibling after a input field is filled out. So if the first name input field is filled out, add a class to the email input field, if the email input field is filled out, add a class to the next input field and so on...

This is my code so far:

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


My HTML looks like this:

<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>

Answer

Grab all the inputs except the submit button into a collection.

On input, show the class of the next input if the current input has a value:

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

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

Fiddle

Snippet:

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

inputs.on('input', function(idx) {
  $(inputs[inputs.index(this) + 1]).toggleClass('animated pulse', 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>

Comments