Amit Kumar
Amit Kumar

Reputation: 5962

Get The Index Of Ul

There two Ul tag on my page . this is my code

HtML:

<div id="accordion">
   <h3>Funeral</h3>
   <div>
    <ul>
      <li><input type="radio" name="rbPlanname" class="rbPlanname" /> Funeral Plan 1</li>
      <li><input type="radio" name="rbPlanname" class="rbPlanname" /> Funeral Plan 2</li>
      <li><input type="radio" name="rbPlanname" class="rbPlanname" /> Funeral Plan 3</li>
    </ul>
   </div>
   <h3>Disability</h3>
   <div>
    <ul>
      <li><input type="radio" name="rbPlanname" class="rbPlanname" /> Disability Plan 1</li>
      <li><input type="radio" name="rbPlanname" class="rbPlanname" /> Disability Plan 2</li>
      <li><input type="radio" name="rbPlanname" class="rbPlanname" /> Disability Plan 3</li>
     </ul>
   </div>
 </div>
 <table width="100%" style="margin-top:26px"> 

JS:

 var planName;
 $('#btnNextClaim').on('click', function () {
   $('.rbPlanname').each(function () {
       if ($(this).is(':checked')) {
         planName = $(this).closest('li').text();
         alert($(this).closest('ul').index());
       }
   });
 });

i want , when user click on next button , then i'm finding which radio button is checked, according to that , i want to find the index of ul. let suppose i radio button from first ul is checked , then it should return 0. here is my fiddle

JsFiddle

Upvotes: 1

Views: 101

Answers (2)

Vikram
Vikram

Reputation: 715

Try this code:

$('#btnNextClaim').on('click', function () {
         $('.rbPlanname').each(function () {
         if ($(this).is(':checked')) {
             planName = $(this).closest('li').text();
             var $ul=$(this).closest('ul');
             alert($('ul').index($ul));
         }
     });
});

DEMO

EDIT-Caching $(this):

We should cache the DOM element,if used frequently in our code:

$('#btnNextClaim').on('click', function () {
    $('.rbPlanname').each(function () {
        var $this=$(this);
        if ($this.is(':checked')) {
            planName = $this.closest('li').text();
            var $ul=$this.closest('ul');
            alert($('ul').index($ul));
        }
    });
});

Upvotes: 1

TJR
TJR

Reputation: 6577

Add to your index() method what kind of index are you looking for. In your case it should be ul

See this http://jsfiddle.net/5awT9/3

Upvotes: 0

Related Questions