How to detect selected checkbox/radio elements in jQuery Mobile framework

jquery

How to detect selected checkbox/radio elements in jQuery Mobile Framework

Well! detecting checked OR radio elements seems no difficult task as far as JQuery is concerned. But here I will discuss some small points (which may fill your knowledge gaps) and finally will provide a fully tested jQuery code that detects checked OR radio elements for jQuery mobile framework.

First let me show you what jQuery mobile does for you in case of checkbox.

<input class="class1" type="checkbox" name="chkbx" id="checkBox1">
<label class="class1 ui-btn ui-corner-all ui-btn-inherit ui-btn-icon-left ui-checkbox-on" for="checkBox1">This is a label for checkBox1.</label>

Now in the above code (jQuery mobile will generate this code for you in case of checkbox), input element with id “checkBox1” is of type checkbox and has a label for it.

A point to note, that in jQuery Mobile detecting checked elements is not merely checking for checked/unchecked status but also you need to check for ui-checkbox-on/ui-checkbox-off class.

Same goes for radio elements.

<label for="radio1" class="ui-btn ui-corner-all ui-btn-inherit ui-btn-icon-left ui-radio-on">This is label for radio1</label>
<input type="radio" name="promoMailers" id="radio1">

we all know that in jQuery selector is important, So how you choose selector for checkbox/radio (apart from using id or class)

$( ":checkbox" )

OR

$( "[type=checkbox]" )

It is good practice to precede it with a tag name

so $( "input:checkbox" ) should be used instead.

So, now after going through basics let’s do some serious coding for detecting checked checkbox elements in a page.

$("input:checkbox").each(function(){
   var $this = $(this);
    var $thisLabel=$("label[for='" + this.id + "']");
     if($this.is(":checked") && $thisLabel.hasClass("ui-checkbox-on")){
    	 //Here you have detected checked element. Execute your logic here.
     }
});

And, same logic goes for detecting checked radio elements.

$("input:checkbox").each(function(){
   var $this = $(this);
    var $thisLabel=$("label[for='" + this.id + "']");
     if($this.is(":checked") && $thisLabel.hasClass("ui-radio-on")){
    	 //Here you have detected checked radio element. Execute your logic here.
     }
});

!!!!!!!!! Sweet

About Anoop Kumar Rai