Multiple html element selection using jquery

Sometimes to select 1 or more element using javascript will cause in mess of Codes.
Jquery comes handy when we thing about the html element selection and add validation.

The below code will help you when, in just 1 page of code you have repeated element of similar type like (multiple textbox ,multiple checkbox etc).

Suppose you have 3 Textbox in your page, You want to count total number of textbox on your page.
Following is the code to count

Html code for multiple Textbox

1
2
3
<input class="tboxClass" type="textbox" name="data[]" />
<input class="tboxClass" type="textbox" name="data[]" />
<input class="tboxClass" type="textbox" name="data[]" />

If you consider above code in all those 3 textbox ,we have same class name i.e “tboxClass”

Jquery code for Html element selection using  Class Name

1
2
3
4
5
6
7
function countTextbox(){
  var totalTextbox = 0;
  $('.tboxClass').each(function(){
    totalTextbox++;
  });
  alert('You have total '+totalTextbox+' Textboxes');
}

In the above jquery html element counter, i am using jquery “each” loop concept.

I am checking total number of element which have class name as “tboxClass” , jquery will search entire page and loop will continue till it finds the last html element which contains the class name as “tboxClass”.

The same thing can be archived using different jquery approach like follows

Jquery code for Html element selection using  Tag Name

1
2
3
4
5
6
7
function countTextbox(){
  var totalTextbox = 0;
  $('input').each(function(){
    totalTextbox++;
  });
  alert('You have total '+totalTextbox+' Textboxes');
}

The above code will help you, finding elements which tag name is “input”, because all our textbox type html element tag name is “input”.

Jquery code for Html element selection using  Attribute with value

1
2
3
4
5
6
7
function countTextbox(){
  var totalTextbox = 0;
  $("[type='textbox']").each(function(){
    totalTextbox++;
  });
  alert('You have total '+totalTextbox+' Textboxes');
}

The above code will search for elements haveing attribute as “type” and that attribute must have value like “textobx”.

Similarly for checkbox we can write code like below

1
2
3
4
5
6
7
function countTextbox(){
  var totalTextbox = 0;
  $("[type='checkbox']").each(function(){
    totalTextbox++;
  });
  alert('You have total '+totalTextbox+' Textboxes');
}

How to get multiple Textbox value using jquery

1
2
3
4
5
function getValuesTextbox(){
  $(".tboxClass").each(function(){
     alert( $(this).val() );
  });
}

The above code will give you values of multiple Textbox.Inside of each loop of jquery we can write $(this) to get reference to current loop element.