Basics of jQuery - Part 2 (Selectors in JQuery)

This is part 2 of Basics of JQuery.

In part 1 of this series we discussed the purpose of using JQuery.

This article discusses the following topics:

  1. Introduction to JQuery Selector
  2. Different types of Selectors

    • Id selector
    • Element TagName selector
    • Class selector
    • Attribute selector
    • Attribute value selector
    • Case insensitive attribute selector
    • Input and :input selector.
    • Checked selector
    • Selected selector

In a CSS article we discussed the purpose of using selectors. In order to select and manipulate the HTML element using its id we used id selector and for class we used class selector. Just like that in JQuery we use the same selector to manipulate the elements.

Let’s look at each of the selectors one by one with a help of a demo.

Id Selector

To select element using its id, we use Id selector.

Demo

In this demo we will see how to select and manipulate an HTML element using its Id.

First thing we need to do is add a textbox control and a button control.

  1. <body>  
  2.    <input type="text" id="txtOne" />  
  3.    <input type="button" id="btn" value="Click" />  
  4. </body>  
In the above HTML element, the id of textbox control is txtOne and id of button is btn.

Now what we want to achieve here is that whenever a user clicks the button, a welcome text should be displayed in the textbox.

Add the following JQuery file reference in the head section your document.
  1. <script src="scripts/jquery-2.1.4.js"></script>  
Write the following JavaScript code.
  1. <script type="text/javascript" lang="ja">  
  2.    $(document).ready(function () {  
  3.   
  4.    });  
  5. </script>  
We have already discussed the purpose of $(document).ready() function in the previous article.

In CSS whenever we want to select an element based on its id, we used #idName whereas in JQuery we use JQuery() function or simply $() and pass an id prefixed with #.

prefixed

Pass the button id as a parameter in the JQuery function and on this function invoke the click event on which create a new anonymous function.
  1. $(document).ready(function () {  
  2.    $('#btn').click(function () {  
  3.   
  4.    });  
  5. });  
Whenever a user clicks the button, we want to display a greeting message. So, write the following inside the anonymous function block.
  1. <script type="text/javascript" lang="ja">  
  2.    $(document).ready(function () {  
  3.       $('#btn').click(function () {  
  4.          $('#txtOne').val('Hello User!');  
  5.       });  
  6.    });  
  7. </script>  
Entire HTML look like this.
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <script src="scripts/jquery-2.1.4.js"></script>  
  5.         <script type="text/javascript" lang="ja">  
  6. $(document).ready(function () {  
  7. $('#btn').click(function () {  
  8. $('#txtOne').val('Hello User!');  
  9. });  
  10. });  
  11. </script>  
  12.         <title></title>  
  13.     </head>  
  14.     <body>  
  15.         <input type="text" id="txtOne" />  
  16.         <input type="button" id="btn" value="Click" />  
  17.     </body>  
  18. </html>  
Run the application

txtOne

Click the button.

button

Useful Tips
  1. JQuery(‘#idSelector’) uses the JavaScript’s document.getElementById() function.

  2. The id of each and every element in your HTML document must be unique. If there are more than one element having the same id then JQuery #id selector returns only the first element.
    1. <body>  
    2.     <input type="text" id="txtOne" />  
    3.     <input type="text" id="txtOne" placeholder="text box two" />  
    4.     <input type="button" id="btn" value="Click" />  
    5. </body>  

    Currently in our document we have two textbox with a same id.

    Let’s see what will happen if we click the button.

    we click the button

    In the output above, the JQuery #id selector returns only the first element.

    Note

    All the selector returns a collection of elements. And since id selector returns only the first element back, so it will have only one element in the collection.

  3. If the element with a given id is not found then JavaScript’s document.getElementById() function throws an error whereas the #id selector JQuery will not throw any error.

  4. Use document.getElementById() over JQuery #id selector unless you need some extra functionality provided by the JQuery object as document.getElementById() is faster than JQuery #id selector.

Element Selector or TagName Selector

To select an element or elements by tag name, use JQuery Element Selector.

Syntax –

$(‘ElementName’)

Demo

In this demo we will see how to count and retrieve total td present in a table, we will also see how to change the background color of all the table row and in addition to that we will see how to display the table content in an alert window.

Create a new HTML document and write the following –

  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <script src="scripts/jquery-2.1.4.js"></script>  
  5.         <title></title>  
  6.     </head>  
  7.     <body>  
  8.         <table border="1" style="border-collapse:collapse">  
  9.             <tr>  
  10.                 <th>Name</th>  
  11.                 <th>Gender</th>  
  12.                 <th>Course</th>  
  13.             </tr>  
  14.             <tr>  
  15.                 <td>James</td>  
  16.                 <td>Male</td>  
  17.                 <td>ASP.NET</td>  
  18.             </tr>  
  19.             <tr>  
  20.                 <td>Sara</td>  
  21.                 <td>Female</td>  
  22.                 <td>C++</td>  
  23.             </tr>  
  24.             <tr>  
  25.                 <td>Michael</td>  
  26.                 <td>Male</td>  
  27.                 <td>PHP</td>  
  28.             </tr>  
  29.         </table>  
  30.     </body>  
  31. </html>  
Run the application

application

Example 1

In this example we will see how to count the table td present in the above table.
  1. <script type="text/javascript">  
  2.    $(document).ready(function () {  
  3.       alert($('td').length);//td is a TagName and length property will give us the total number of td present in the table.  
  4.    });  
  5. </script>  
count the table td

Example 2

In this example we will display all the data in an alert window.
  1. <script type="text/javascript">  
  2.    $(document).ready(function () {  
  3.       alert($('table').html());//the html() function will return the document in an HTML format.  
  4.    });  
  5. </script>  
display all the data

Example 3

In this example we will see how to change the background color of the table rows.
  1. <script type="text/javascript">  
  2.    $(document).ready(function () {  
  3.       $('tr').css('background-color''green');//css() function can be used to change the background color of any element. The first parameter is the property name and the second parameter is the value.  
  4.    });  
  5. </script>  
change the background color image

Example 4

In this example we will create two tables and we will see how to change the background color of one and both the tables using even and odd selector.

change the background color

The first table have an id of t1 and second table have an id of t2.

Now let’s see how to change the background color of both these tables.
  1. $(document).ready(function () {  
  2.    $('tr').css('background-color''red');  
  3. });  
create two tables
Let’s say our requirement is such that we want to change the 1st and 3rd row color to red and the rest of the rows to yellow. To achieve this functionality we can use even and odd selector.
  1. $(document).ready(function () {  
  2.    $('tr:even').css('background-color''red');  
  3. });  
tables
  1. $(document).ready(function () {  
  2.    $('tr:even').css('background-color''red');  
  3.    $('tr:odd').css('background-color''yellow');  
  4. });  
odd selector

In the output above, both the tables works exact the same way. But what if we want only the second table background color to be manipulated. Is it possible to achieve that functionality? Absolutely.
  1. $(document).ready(function () {  
  2.    $('#t2 tr:even').css('background-color''red');  
  3.    $('#t2 tr:odd').css('background-color''yellow');  
  4. });  
set background

Class Selector

To select one or more than one element using their css class name, class selector can be used. In JavaScript for selecting and manipulating an element using its class name we use the native document.getElementByClassName function. In JQuery we use JQuery “.class” selector.

Demo

Create a new HTML document and write the following within the body section.
  1. <body>  
  2.     <p class="p1">This is paragraph one</p>  
  3.     <div>  
  4.         <p class="p2">This is paragraph two</p>  
  5.         <p class="p2">This is paragraph three</p>  
  6.         <p class="p4">This is paragraph four</p>  
  7.     </div>  
  8.     <p class="p5">This is paragraph five</p>  
  9. </body>  
Save and run
Save and run

Currently we have five paragraphs out of which the three paragraphs are inside a div section i.e. paragraph two, three, and four. Paragraph two and three have a same class name.

Now let’s see how to select and manipulate all the above elements using JQuery.

Example 1

In this example we will change the background color of paragraph one.

Write the following JavaScript within the head section of your HTML document.
  1. <script src="scripts/jquery-2.1.4.js"></script>  
  2.    <script type="text/javascript" lang="ja">  
  3.       $(document).ready(function () {  
  4.       $('.p1').css('background-color''green');  
  5.    });  
  6. </script>  
Run the application

green

Example 2

In this example we will see how to change the background color of p1 and p2.
  1. <script type="text/javascript" lang="ja">  
  2.    $(document).ready(function () {  
  3.       ('.p1, div .p2').css('background-color''red');  
  4.    });  
  5. </script>  
Note: To select and manipulate more than one element, we specify class name each separated by comma(,).

.p1, div .p2, where .p1 is a class name of paragraph one and div .p2 is like a descendent selector which means inside the div section there is an element with a class name p2.

Run the application

Run

Attribute and Attribute value selector

The Attribute Selector of JQuery is used to select elements that have specific attributes.

The Attribute Value Selector of JQuery is used to select elements that have a specified attribute values.

Syntax

$(‘[AttributeName]’)
$(‘[AttributeName = Value]’)


Let’s look at some of the examples of it.

Example 1

In this example we will see how to select and change the background color of three paragraph elements using its attribute and in order to do that we need to create a new HTML document.

Add three paragraphs in the body section.
  1. <p title="p1">This is paragraph one</p>  
  2. <p title="p1">This is paragraph two</p>  
  3. <p title="p2">This is paragraph three</p>  
Add the following reference to the JQuery file in the head section.
  1. <script src="scripts/jquery-2.1.4.js"></script>  
Write the following JQuery code.
  1. <script type="text/javascript" lang="ja">  
  2.    $('[title]').css('background-color''red');//title is one of the attribute of paragraph element on which we invoked the css function which will change the  background color of all the three paragraphs.  
  3. </script>  
Note: It is mandatory to wrap the attribute name inside the square bracket.

The entire HTML look like this.
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <title></title>  
  5.         <script src="scripts/jquery-2.1.4.js"></script>  
  6.     </head>  
  7.     <body>  
  8.         <p title="p1">This is paragraph one</p>  
  9.         <p title="p1">This is paragraph two</p>  
  10.         <p title="p2">This is paragraph three</p>  
  11.         <script type="text/javascript" lang="ja">  
  12. $('[title]').css('background-color''red');  
  13. </script>  
  14.     </body>  
  15. </html>  
background color

Example 2

In this example we will see how to change the background color of the above three paragraphs using its attribute values and in order to do that we need to make some changes in our script.
  1. <!--Attribute value-->  
  2.    <script type="text/javascript" lang="ja">  
  3.       $('[title=p1]').css('background-color''orange');  
  4.    </script>  
$('[title=p1]') where title is an attribute and p1 is a value of this title attribute.

As we know, in our application there are two paragraphs whose title value is p1. So, when we run the application the background color of those two paragraphs will change to orange.

Run the application

Run the application

Example 3

In this example we will see how to manipulate only those paragraphs which is present inside a div section and in order to do that we need to make some modification in our body section.

Wrap the first paragraph inside a div section.
  1. <div>  
  2.    <p title="p1">This is paragraph one</p>  
  3. </div>  
  4. <p title="p1">This is paragraph two</p>  
  5. <p title="p2">This is paragraph three</p>  
Write the following JQuery –
  1. <script type="text/javascript" lang="ja">  
  2.    $('div p[title=”p1”]').css('background-color''green');  
  3. </script>  
background

Example 4

In this example we will see how manipulate elements based on two attributes. In order to achieve it we need to make some changes in the body section.
  1. <p title="p1" class=".p1">This is paragraph one</p>  
  2. <p title="p1" class=".p2">This is paragraph two</p>  
  3. <p title="p2" class=".p1">This is paragraph three</p>  
At the moment, we have two attributes in the first two paragraphs i.e. title with a value of p1 and class with a value of p1 and p2 respectively.

Now in order to add a background-color or a border to the first paragraph we can use title attribute. But at present all the three paragraphs have title attributes. We can use attribute value but still there are two paragraphs whose value is same. So in order to add border to the first paragraph, we can specify two attribute with its values.
  1. <!--More than one attribute-->  
  2.    <script type="text/javascript" lang="ja">  
  3.    $("[title='p1'][class='.p1']").css('border''3px green dotted');  
  4. </script>  
How does it works?
  1. [title='p1'][class='.p1']  
Add a border to an element whose title is p1 and class is .p1.

Add a border

Now you might be wondering what will happen if we specify a comma between those attributes.
If you specify comma between the two attributes, it will be treated as OR.
  1. <script type="text/javascript" lang="ja">  
  2.    $("[title='p1'],[class='.p1']").css('border''3px green dotted');  
  3. </script>  
specify comma

Some important points to remember when working with Attribute Value selector.

Attribute Value Selectors can be categorized into following –

Equal Selector [title=”value”] => The EqualTo Value Selector can be used in a situation where you want to manipulate only those element which matches the specified attribute value.

Example
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <title></title>  
  5.         <script src="../scripts/jquery-2.1.4.js"></script>  
  6.         <meta charset="utf-8" />  
  7.     </head>  
  8.     <body>  
  9.         <p title="title1">This is paragraph one</p>  
  10.         <p title="title2">This is paragraph two</p>  
  11.         <p title="title1">This is paragraph three</p>  
  12.         <script type="text/javascript" lang="ja">  
  13. $(document).ready(function () {  
  14. $('[title=\'title1\']').css('color''green');  
  15. });  
  16. </script>  
  17.     </body>  
  18. </html>  
  19.   
  20. $('[title=\'title1\']').css('color''green');  
The above syntax states, fore-color will be changed for those elements whose title attribute value is equal to title1.

Output

fore color

Not Equal Selector [title!=”value”] => Not EqualTo Value Selector can be used in a situation where you want to manipulate only those element which does not matches the specified attribute value.

Example
  1. $('[title!=\'title1\']').css('color''green');  
The above syntax states, the fore-color will be changed for those elements whose attribute value is not equal to title1.

Output

title1

StartsWith Selector [title^=”value”] => StartsWith Attribute Selector selects all the elements whose attribute value starts with a specified string and here the string is ‘value’.

Example
  1. <p title="title1">This is paragraph one</p>  
  2. <p title="title2">This is paragraph two</p>  
  3. <p title="21">This is paragraph three</p>  
In the above HTML, the title value of the first two paragraph is title1 and title2. The title value of the last paragraph is 21.

Write the following JQuery.
  1. <script type="text/javascript" lang="ja">  
  2.    $(document).ready(function () {  
  3.       $('[title^="t"]').css('color''green');  
  4.    });  
  5. </script>  
In the above JQuery syntax, we are looking for only those title attributes whose value starts with t and once those elements are found, the CSS function will change the fore-color of those elements.

Entire HTML look like this.
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <title></title>  
  5.         <script src="../scripts/jquery-2.1.4.js"></script>  
  6.         <meta charset="utf-8" />  
  7.     </head>  
  8.     <body>  
  9.         <p title="title1">This is paragraph one</p>  
  10.         <p title="title2">This is paragraph two</p>  
  11.         <p title="21">This is paragraph three</p>  
  12.         <script type="text/javascript" lang="ja">  
  13. $(document).ready(function () {  
  14. $('[title^="t"]').css('color''green');  
  15. });  
  16. </script>  
  17.     </body>  
  18. </html>  
Output

hHTML look

EndsWith Selector [title$=”value”] => EndsWith Selector is just opposite of StartsWith Attribute value selector. To check if the element value ends with a specific string, we use “$”.

Example
  1. $('[title$="1"]').css('color''green');  
Output

value selector

There are some more selectors that you can use.

Contains Selector [title*=”value”] =>
element must contain the word “value” in the title attribute.

Syntax –

<p title=”thisvalue”></p>

Contains Word Selector [title~=”value”] => element must contain the word “value” in the title attribute, but it should be delimited by space.

Syntax –

<p title=”this value”></p>

Contains Prefix Selector [title |=”value”] => element attribute value must be equal to the word “value” or the word “value” must be followed by a hypen(-).

Syntax –

<p title=”value”></p>
<p title=”value-title”></p>

Case In-Sensitive Attribute Selector

JQuery Attribute value selector is case-sensitive, meaning attribute value ABC is different from abc.
First let’s look at an example of case-sensitive attribute value then we will see how to make it case-insensitive.

Example

In the body section of my HTML document, I have three paragraphs.
  1. <p title="title1">This is paragraph one</p>  
  2. <p title="Title1">This is paragraph two</p>  
  3. <p title="TiTle1">This is paragraph three</p>  
Look at the title attribute values of all the paragraphs. Each title value is a mixture of upper and lower case.

Let’s say we want to change the fore-color of those elements whose title value is title1.
  1. <script type="text/javascript" lang="ja">  
  2.    $('[title="title1"]').css('color''green');  
  3. </script>  
Entire HTML look like this.
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <title></title>  
  5.         <script src="../scripts/jquery-2.1.4.js"></script>  
  6.         <meta charset="utf-8" />  
  7.     </head>  
  8.     <body>  
  9.         <p title="title1">This is paragraph one</p>  
  10.         <p title="Title1">This is paragraph two</p>  
  11.         <p title="TiTle1">This is paragraph three</p>  
  12.         <script type="text/javascript" lang="ja">  
  13. $(document).ready(function () {  
  14. $('[title="title1"]').css('color''green');  
  15. });  
  16. </script>  
  17.     </body>  
  18. </html>  
Output

Since JQuery attribute value selector is case-sensitive, so only the first paragraph fore-color will change.



Now let’s see how to make it case-insensitive.

Example 2

There are three ways to make attribute value case-insensitive.

 

  1. To make attribute value case-insensitive we can use the filter function.
    1. <script type="text/javascript" lang="ja">  
    2.    $(document).ready(function () {  
    3.       $('[title]').filter(function () {  
    4.          return $(this).attr('title').toLowerCase() == 'title1';  
    5.       }).css('color''green');  
    6.    });  
    7. </script>  
    Explanation

    $('[title]').filter(function () {})

    In this piece of code, we invoked the filter function on the JQuery function.

    The filter function expects a selector as a parameter.

    selector

    So, we have created a new anonymous function which will give us the case-insensitive selector back.
    1. return $(this).attr('title').toLowerCase() == 'title1';  
    The attr function will give us the value of the attribute title, which we are converting to lowercase using ToLowerCase function and in addition to that we are also checking if the returning value is equal to title1. If it is false then the filter function will remove/filter those elements from displaying and will only display those elements whose attribute value is equal to title1 ignoring the case. In short we are comparing the returning value with the value we specified and on this filter function we invoked the css function which will change the fore-color.

    Output

    color

  2. There is also another way to achieve the same. We can use the test function.
    1. <script type="text/javascript" lang="ja">  
    2. $(document).ready(function () {  
    3.    $('[title]').filter(function () {  
    4.       return (/title1/i).test($(this).attr('title'));  
    5.    }).css('color''green');  
    6. });  
    7. </script>  
    8.   
    9. return (/title1/i).test($(this).attr('title'));  
    The test function compares the returning value from the attr function with the value title1.

    /title1/i “i” stands means the comparison must be case-insensitive.

  3. We can use the RegExp function itself and on that we can call the test function and these expression must be wrapped inside the filter function.
    1. <script type="text/javascript" lang="ja">  
    2.    $('[title]').filter(function () {  
    3.       return(RegExp('title1','i').test($(this).attr('title')));  
    4.    }).css('color''green');  
    5. </script>  

Input and : input selectors

$(:input)selector selects all input tag elements, select elements, textarea, button, etc.

Let’s look at an example.

  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <title></title>  
  5.         <script src="scripts/jquery-2.1.4.js"></script>  
  6.         <meta charset="utf-8" />  
  7.     </head>  
  8.     <body>  
  9.         <p>Input element type text</p>  
  10. State   
  11.         <input type="text" value="Jharkhand" />  
  12. City   
  13.         <input type="text" value="Bokaro" />  
  14.         <br />  
  15.         <p>Input element type radio</p>  
  16. Gender:  
  17.         <input type="radio" name="Gender" checked="checked" value="Male" />Male  
  18.   
  19.         <input type="radio" name=" Gender" value="Female" />Female  
  20.   
  21.   
  22.         <p>Dropdownlist using Select element</p>  
  23.         <select>  
  24.             <option value="Microsoft" selected="selected">Microsoft</option>  
  25.             <option value="Google">Google</option>  
  26.             <option value="Apple">Apple</option>  
  27.         </select>  
  28.         <br />  
  29.         <p>Text area and button</p>  
  30.         <textarea>This is text area</textarea>  
  31.         <br />  
  32.         <input type="button" value="Button" />  
  33.     </body>  
  34. </html>  
In the above HTML, we have five input elements, one select element, and a textarea.

Output

input elements

Let’s see how to print the values in a JavaScript alert box.
  1. <script type="text/javascript" lang="ja">  
  2.    $(document).ready(function () {  
  3.       $(':input').each(function () {  
  4.       alert($(this).val());  
  5.    });  
  6. });  
  7. </script>  
Note: Each function is used to iterate through a condition until the condition remains true.
Val function is used to retrieve the value back.

Since, we are using “:input” selector, it will print all the element values on the alert box.

Output

input

Click ok

print button

Click ok

It will print the rest and in the end it will print button value.

print the rest

$(input) selector selects only the input tag elements.

Let’s look at the same example that we discussed in :input selector.

In the script section, remove the “:” from the input element and run the application.
  1. <script type="text/javascript" lang="ja">  
  2.    $(document).ready(function () {  
  3.       $(‘input').each(function () {  
  4.       alert($(this).val());  
  5.    });  
  6. });  
  7. </script>  
Output

It will print the textbox, radio button, and button value because these elements are of type input and the rest is different.

Now let’s say for some reason we want to retrieve the value of only those input element whose type is radio and for that we can combine the input or :input selector with attribute value selector.

For input element
  1. $('input[type=\'radio\']').each(function () {  
  2.    alert($(this).val());  
  3. });  
  4. </script>  
For : input element
  1. $('input[type=\'radio\']').each(function () {  
  2.    alert($(this).val());  
  3. });  
  4. </script>  
Output

input element

Click ok

Click ok

Checked Selector

The JQuery :checked selector selects all the checked radio buttons and checkboxes.

Let’s look at an example of radio button first.

Add two radio buttons and a button control.
  1. <body>  
  2.     <input type="radio" name="Gender" value="Male" />Male  
  3.   
  4.     <input type="radio" name="Gender" value="Female" />Female  
  5.   
  6.     <br/>  
  7.     <input type="button" id="btn" value="Click" />  
  8. </body>  
Output

select

Whenever user selects a radio button and clicks the button, we want to display the value of that particular radio button in an alert window and for that we need to write some JQuery codes.
  1. < script type = "text/javascript"  
  2. lang = "ja" >  
  3. //generate a click event on the button control and create an anonymous function  
  4. $(document).ready(function() {  
  5.     $('#btn').click(function() {  
  6.         //check for only those input elements whose type is radio and which is checked  
  7.         var value = $('input[type=\'radio\']:checked');  
  8.         //if the length is greater than 0 which means there is something inside the value variable  
  9.         if (value.length > 0) {  
  10.             //retrieve the data from the value variable using the val function  
  11.             alert(value.val() + ' is checked');  
  12.         } else {  
  13.             alert('Please select an option');  
  14.         }  
  15.     });  
  16. }); < /script>  
Note: As we know radio button will give us only a single checked item back, so there is no point in looping through each radio button element.

Output

click

Click the button without selecting any option.

Click the button

Select Male and click the button.

Select Male

Select Female.

ok

Now let’s see how to achieve the same thing in checkbox control.

Example

Write the following to generate four checkbox control, a button control and a span element.
  1. <body>  
  2. Interests:  
  3.   
  4.     <input type="checkbox" value="Programming" />Programming  
  5.   
  6.     <input type="checkbox" value="Gaming" />Gaming  
  7.   
  8.     <input type="checkbox" value="Blogging" />Blogging  
  9.   
  10.     <input type="checkbox" value="Photography" />Photography  
  11.   
  12.     <br />  
  13.     <input type="button" value="Submit" id="btn" />  
  14.     <span id="spanArea" style="display:block"></span>  
  15. </body>  
Output

Photography

Whenever user clicks the button, we want to display the selected value. So, write the following JQuery.
  1. < script type = "text/javascript"  
  2. lang = "ja" > $(document).ready(function() {  
  3.     $('#btn').click(function() {  
  4.         //retireve all the checked items whose input type is checkbox  
  5.         var checkedItems = $('input[type=\'checkbox\']:checked');  
  6.         if (checkedItems.length > 0) {  
  7.             //create a new variable that will hold the checked items  
  8.             var NumberOfCheckedItems = "";  
  9.             $(checkedItems).each(function() {  
  10.                 //with the help of each function, we will get the total checkedItems on which we invoked the val() function and this val function will give us the checked value  
  11.                 NumberOfCheckedItems += $(this).val() + "<br/>";  
  12.             });  
  13.             $('#spanArea').html(NumberOfCheckedItems);  
  14.         } else {  
  15.             $('#spanArea').html('No checkbox checked');  
  16.         }  
  17.     });  
  18. }); < /script>  
Output

No checkbox checked

If checkboxes belongs to the same group it is very easy to select the values of the selected checkboxes. But what if the checkboxes are in different groups and we want to select the values of those checked checkboxes.

At the moment in our there is only one group of checkboxes i.e. Interests group.

Let’s add another group.

Movie Genres:
  1. <input type="checkbox" value="Biography" />Biography  
  2. <input type="checkbox" value="Thriller" />Thriller  
  3. <input type="checkbox" value="Action" />Action  
  4. <input type="checkbox" value="Romance" />Romance  
Output

Biography

So we have two different groups of checkboxes.

Now, what will happen if we write the same JQuery we wrote for the single checkbox group?
  1. < script type = "text/javascript"  
  2. lang = "ja" > $(document).ready(function() {  
  3.     $('#btn').click(function() {  
  4.         var checkedItems = $('input[type=\'checkbox\']:checked');  
  5.         if (checkedItems.length > 0) {  
  6.             var NumberOfCheckedItems = "";  
  7.             $(checkedItems).each(function() {  
  8.                 NumberOfCheckedItems += $(this).val() + "<br/>";  
  9.             });  
  10.             $('#spanArea').html(NumberOfCheckedItems);  
  11.         } else {  
  12.             $('#spanArea').html('No checkbox checked');  
  13.         }  
  14.     });  
  15. }); < /script>  
This $('input[type=\'checkbox\']:checked') is going to select all the checked items from both the groups.

Output

checked items

So, how to overcome this problem?

Let’s divide the procedure into multiple steps. 
  1. Remove the button control and add another span element.
    1. <span id="spanInterest" style="display:block"></span>  
    2. <br/>  
    3. <span id="spanMovie" style="display:block"></span>  
    Give both the group of checkboxes a name. For interest group give a name Interest and for Movie Genres group give a name Movie.

    Interests:
    1. <input type="checkbox" value="Programming" name="Interest" />Programming  
    2. <input type="checkbox" value="Gaming" name="Interest" />Gaming  
    3. <input type="checkbox" value="Blogging" name="Interest" />Blogging  
    4. <input type="checkbox" value="Photography" name="Interest" />Photography  
    5. <br />  
    Movie Genres:
    1. <input type="checkbox" value="Biography" name="Movie" />Biography  
    2. <input type="checkbox" value="Thriller" name="Movie" />Thriller  
    3. <input type="checkbox" value="Action" name="Movie"/>Action  
    4. <input type="checkbox" value="Romance" name="Movie"/>Romance  
  2. Create a separate function.
    1. //create as a separate function for the JQuery we wrote  
    2. var checkedFunction = function(Group) {  
    3.     var checkedItems = $('input[name="' + Group + '"]:checked');  
    4.     if (checkedItems.length > 0) {  
    5.         var numberOfCheckedItems = "";  
    6.         $(checkedItems).each(function() {  
    7.             numberOfCheckedItems += $(this).val() + "<br/>";  
    8.         });  
    9.         $('#span' + Group).html(numberOfCheckedItems);  
    10.     } else {  
    11.         $('#span' + Group).html('no item selected');  
    12.     }  
    13. };  
    The above script is exactly the same. The only thing we did is that instead of passing the input name value, we passed a Group variable which is a parameter of this function to make it re-usable.

  3. Generate two click events inside which create a new anonymous function which will invoke the checkedFunction(Group).
    1. $('input[name="Interest"]').click(function() {  
    2.     checkedFunction('Interest');  
    3. });  
    4.   
    5. $('input[name="Movie"]').click(function() {  
    6.     checkedFunction('Movie');  
    7. });  
    The Entire HTML look like this.
    1. <!DOCTYPE html>  
    2. <html>  
    3.     <head>  
    4.         <title></title>  
    5.         <meta charset="utf-8" />  
    6.         <script src="../scripts/jquery-2.1.4.js"></script>  
    7.     </head>  
    8. <body>  
    Interests:
    1. <input type="checkbox" value="Programming" name="Interest" />Programming  
    2.   
    3. <input type="checkbox" value="Gaming" name="Interest" />Gaming  
    4.   
    5. <input type="checkbox" value="Blogging" name="Interest" />Blogging  
    6.   
    7. <input type="checkbox" value="Photography" name="Interest" />Photography  
    8.   
    9. <br />  
    Movie Genres:
    1. <input type="checkbox" value="Biography" name="Movie" />Biography  
    2.   
    3. <input type="checkbox" value="Thriller" name="Movie" />Thriller  
    4.   
    5. <input type="checkbox" value="Action" name="Movie" />Action  
    6.   
    7. <input type="checkbox" value="Romance" name="Movie" />Romance  
    8.   
    9. <br />  
    10. <span>  
    11.     <b>Interest Group</b>  
    12. </span>  
    13. <span id="spanInterest" style="display:block"></span>  
    14. <br />  
    15. <span>  
    16.     <b>Movie Genres Group</b>  
    17. </span>  
    18. <span id="spanMovie" style="display:block"></span>  
    19. <script type="text/javascript" lang="ja">  
    20.    //create as a separate function for the JQuery we wrote  
    21.    var checkedFunction = function (Group) {  
    22.       var checkedItems = $('input[name="' + Group + '"]:checked');  
    23.       if (checkedItems.length > 0) {  
    24.          var numberOfCheckedItems = "";  
    25.          $(checkedItems).each(function () {  
    26.             numberOfCheckedItems += $(this).val() + "  
    27.              <br/>";  
    28.          });  
    29.          $('#span' + Group).html(numberOfCheckedItems);  
    30.       }  
    31.       else {  
    32.          $('#span' + Group).html('no item selected');  
    33.       }  
    34.    };  
    35.   
    36.    $('input[name="Interest"]').click(function () {  
    37.       checkedFunction('Interest');//pass the Group as Interest  
    38.    });  
    39.   
    40.    $('input[name="Movie"]').click(function () {  
    41.       checkedFunction('Movie');  
    42. });  
    43.   
    44.   
    45. </script>undefined</body>undefined</html>  
    Output

    Movie Genres

    If you uncheck any of the checkbox, it will remove the un-checked one.

    checkbox

Selected Selector

To select all the selected options from a select element, use :selected selector.

Let’s look at an example.

Write the following HTML code.

  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <title></title>  
  5.         <meta charset="utf-8" />  
  6.     </head>  
  7.     <body>  
  8.         <select id="selectLang">  
  9.             <option value="js">JavaScript</option>  
  10.             <option value="vb">Visual Basic</option>  
  11.             <option value="php">Hypertext PreProcessor</option>  
  12.         </select>  
  13.         <br />  
  14.         <span id="spanLang" style="display:block"></span>  
  15.     </body>  
  16. </html>  
Output

display

Whenever a user selects any of the option, we want to display the value and text of the selected option.

Write the following JQuery –
  1. < script type = "text/javascript" > $(document).ready(function() {  
  2.     //whenever user changes the option, the change function will be invoked  
  3.     $('#selectLang').change(function() {  
  4.         //once the change function is invoked, all the selected options present in a Select element with an id selectLang will be stored in a selectedOption varialbe  
  5.         var selectedOption = $('#selectLang option:selected');  
  6.         //with the help of selectedOption variable we would be able to retrieve the value using the val function and text using the text function  
  7.         $('#spanLang').html('Value= ' + selectedOption.val() + 'Text= ' + selectedOption.text());  
  8.     });  
  9. }); < /script>  
Output

Output

Now let’s see how to retrieve the value and text of more than one selected option.
  1. < script type = "text/javascript"  
  2. lang = "ja" > $(document).ready(function() {  
  3.     $('#selectLang').change(function() {  
  4.         var choice = $('#selectLang option:selected');  
  5.         if (choice.length > 0) {  
  6.             var selectedOption = '';  
  7.             choice.each(function() {  
  8.                 selectedOption += 'Value = ' + $(this).val() + " Text = " + $(this).text();  
  9.             });  
  10.             $('#spanLang').html(selectedOption);  
  11.         } else {  
  12.             $('#spanLang').html('no option selected');  
  13.         }  
  14.     });  
  15. }); < /script>  
Output

script

Note: Checked selector and Selected sector is exactly the same.

Summary

In this article, we discussed about some of the most useful selectors of JQuery.

To know more about JQuery selector, click here.

I hope you like it. Thank you