views:

67

answers:

2

I have a small JavaScript function that (among other things) retrieves the ID of the last element with a certain class name.

var lastRowID = $(".sectionRow:last").attr('id');

It should find elements in a table that looks similar to the following:

<table>
    <tr id="courseSection[0]" class="sectionRow"><td>stuff</td></tr>
    <tr id="courseSection[1]" class="sectionRow"><td>more stuff</td><td><a href="javascript:removeSectionRow(1)">(remove)</a></td><td><a href="javascript:addSectionRow()">(add additional row)</a></td></tr>
</table>

If I do a quick alert(lastRowID), I get 'courseSection[1]' in Chrome, Firefox, and IE8. However, IE7 hates me and says 'undefined'.

Note: I've also tried $(".sectionRow").last().attr('id') to no success.

Any thoughts on what might be going on? Thanks!

Edit: This table was added using javascript on a button click (button shows / adds next part of the form). So it's not static html that was in the DOM at page load.

The removeSectionRow(n) function is called when the remove link is clicked. It removes the specified row, then searches for the last row remaining with class name "sectionRow" in order to give that row a "add additional row" link. The idea being that the user can add and remove rows at will. Here's a screenshot of the finished result to illustrate what I'm probably poorly explaining: http://imgur.com/uXYHj.png

A: 

Maybe because it's invalid HTML? You need <td> tags in there. Works in IE8 for me.

http://jsfiddle.net/VCpZq/

Mark
The real code has <td>'s in there. And it works fine in IE8, indeed :)
Erik Reynolds
Ah..didn't have IE7 installed. Sorry ;)
Mark
No worries! I didn't either until a user approached me this morning and told me about this bug on IE7. I had to find a machine with IE7 to even replicate it. I ended up using a program called "IETester" which is actually fairly nice (and free!)
Erik Reynolds
+1  A: 

The characters [ and ] are not valid ID characters. Perhaps this is causing some issue in IE7.

Test the quantity of elements returned by the selector to see if you are getting the <tr> or not.

alert( $(".sectionRow:last").length );
patrick dw
Good to know about the brackets! I'll try removing those next. The alert returned 0, so it's not finding any of them.
Erik Reynolds
See this question for some details about what is/isn't valid as an id attribute: http://stackoverflow.com/questions/70579/what-is-a-valid-value-for-id-attributes-in-html
Ender
@Erik - Testing in IE7, I'm not having any issues. Any chance you edited the problem out in your question's code? How about if you do `alert( $(".sectionRow").length );`?
patrick dw
@patrick It's likely -- I just tried the jsfiddle.net link below and my example seems to work fine in IE7. Let me see if I can expand the scope of the context a bit.
Erik Reynolds