tags:

views:

36

answers:

2

I'm having a table in which i'm creating a label dynamically.

'<td>' + '<label for="Name" id = ' + value + '>' + text + '</label></td>'

I want to retrieve the id of the label and I`m doing the following which is not working: How can I get the Id of the label?

function ReadNames() {
            $('#Table tr').each(function() {
                NameID.push($(this).find('label').val());
            });   } 
+1  A: 

First of all, you'll have to you should correct the markup and include quotes for the id:

'<td><label for="Name" id="' + value + '">' + text + '</label></td>'

Next, $('label').attr('id') should get you the id.

deceze
Quotes are often optional around attribute values. http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2
David Dorward
@David Technically yes, okay, but only if the ID conforms to certain constraints (possible characters). Especially when constructing elements dynamically, like the OP, and even when not, you should always go for quotes. It is even recommended in the article you link to. :)
deceze
All of the characters allowed in an id ( http://www.w3.org/TR/html4/types.html#type-name ) are on the list of "No quotes needed" ;)
David Dorward
That said, I'd build my elements with DOM rather than strings, which eliminates the need to worry about quotes (since using standard DOM will deal with escaping and so on for you)
David Dorward
@David But what if the OP used XHTML? :)
deceze
Then I'd rant about how silly it is to use XHTML in a world where we have to support IE < 9 :)
David Dorward
A: 

Assuming you have multiple tr's and each has at least one (or exactly one) label

function ReadNames () {
    $('#Table tr td label').each(function () {
        NameID.push(this.id);
    });
}
jitter