Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 411
ultrasamad Avatar asked Aug 11 '26 21:08

ultrasamad


1 Answers

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>
like image 88
Adam Avatar answered Aug 13 '26 11:08

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!