UI practice #4 Checking whether an element is present using jQuery

How to check whether atleast one input is selected using jQuery

Sometimes, while working with forms, a user is expected to select atleast one input, or a feedback should be thrown asking them to "Select atleast one input".

How to check that using jQuery

When a select option is checked checked attribute is added.
To check whether the any of it is checked :checked is used in jQuery.
If any of the checkbox is having checked attribute, then the user is allowed to submit.



How to check whether an element is present

To check whether an element is present,
1) size() function is used
2) .length property is used
.length is faster than .size() because, former is a property whereas latter is a function.

jQuery length

HTML snippet

$('#submitBtn').click(function(){
  if($('input[type="checkbox"]:checked').length >= 1){
      alert("Is checked");
  }
  else{
      alert("Select atleast one");
  }
});


jQuery length

Other jQuery practice articles
1. jQuery DOM functions and array
2. DOM manipulation in jQuery
3. Daily ui practice - Input range sliders

Follow our FB page



Subscribe to Creative Technocrayts and be a part of growing community.

Comments

Popular posts from this blog

What are some mistakes people make when they start learning HTML, CSS and JavaScript?

How to initialize Datatable plugin?

Datatables.net - Plugin options