ultrasamad ultrasamad - 1 year ago 59
Javascript Question

How to use jQuery toggleClass to optimize code

I wrote this code that validates input fields for empty values.

It works, but I realized with jQuery toggleClass, I might be able to improve upon it or optimize it.

But I can't figure a way out.

Any help will be appreciated.



$(function() {

$('.cont').on('click', '#submit', function(event) {
event.preventDefault();

$('.cont input').filter(function() {

return !this.value.trim();

}).addClass('highlight');

});

//remove red borders if field contains input
$('.cont').find('input').blur(function(event) {
if ($(this).val() && $(this).hasClass('highlight')) {
$(this).removeClass('highlight');
}
});
})

.highlight {
border-color: red
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="cont">
<input type="text" name="firstname" placeholder="Firstname">
<input type="text" name="lastname" placeholder="Lastname">
<button id="submit">Submit</button>
</div>




Answer Source

toggleClass(class) takes a lesser-known second optional boolean argument 'state', so can also be used to remove the class without having to keep track of state...

I'd recommend calculating the state of whether it is valid or not and then passing that to toggleState() so that it will also clear the red border when valid without additional code.

$(function() {

  $('.cont').on('click', '#submit', function(event) {
    event.preventDefault();

    $('.cont input').each(function(it) {
      $(this).toggleClass('highlight', !(this).value.trim());
    });

  });
})
.highlight {
  border: 1px solid red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="cont">
  <input type="text" name="firstname" placeholder="Firstname">
  <input type="text" name="lastname" placeholder="Lastname">
  <button id="submit">Submit</button>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download