views:

16842

answers:

3

New to javascript/jquery and having a hard time with using "this" or "$(this)" to get the current object.

I have a table with a set of radio buttons on each row, each named 's_'. None of the radio buttons are checked by default:

<tr>
   <td align="left" style="width: 300px">
      <div id="div_s_0">
         <input type="radio" name="s_0" value="1" />Public
         <input type="radio" name="s_0" value="2" />Not Public
         <input type="radio" name="s_0" value="3" />Confidential
      </div>
   </td>
</tr>
<tr>
   <td align="left" style="width: 300px">
      <div id="div_s_1">
         <input type="radio" name="s_1" value="1" />Public
         <input type="radio" name="s_1" value="2" />Not Public
         <input type="radio" name="s_1" value="3" />Confidential
      </div>
   </td>
</tr>

I'm trying to write a jQuery function to add a new row to the table whenever the user selects a radio button, but only if they are currently on the last row of the table. What I'd like to do is get the name attribute of the clicked radio button, parse it to get the row index (i.e. the part after the '_') and compare it to the number of rows in the table. If they are equal, add a new row, otherwise, do nothing.

My question is twofold, depending on how I should attack this:

1) How do I return the name attribute of a radio button, OR 2) How do I return the row index of the row I am currently in?

A: 

Here's some untested code, off the top of my head:

$("#div_s_0 input[type='radio']").onclick = function() {
    if ($("#div_s_0 input[type='radio']:last").attr('checked') == 'checked') {
    /* add a new element */
    }
}

What that does is attach an onclick event to each of the radio buttons in the div. The onclick will check if the last radio button in that group is checked, and if so add another element.

Like I said it hasn't been tested yet. I'm unsure about the selector (#div_s_0 ... :last) so give it a run in Firebug first.

MDCore
+3  A: 

This will get you the index, using the HTML you've provided:

$(document).ready(function() {
    $("input:radio").click(function() {
        var index = parseInt(this.name.split('_')[1])
    });
});

Another thing that may help you: retrieving the number of rows in your table:

$($("table").children()[0]).children().length

Hope this helps you on your way.

Ryan Duffield
+2  A: 

For your specific questions 1 & 2, if you gave your table an ID of "mytable", this example should give you what you're looking for:

var rowIndex = $("#mytable tr").index($(this).parents("tr"));
var inputName = $(this).attr("name");
alert("Input Name: " + inputName + "; RowIndex: " + rowIndex);
Pseudo Masochist