jugnu
jugnu

Reputation: 139

accing dynamic element through jquery

I want to achieve this

$("div1 input").attr('id');

where div1 is dynamically generated through php loop ( so i have like div1,div2,div3 etc )

in my jquery function i have $('#counter').val();which holds calues from 1 to 3 dynamically,

so this is what i am doing $("#div"+ $("#counter").val() +"input").attr('id')

above code should give me input attribute id,

for some reasons or may be due to some syntax problem i am not getting it, Have a look and point out my mistake . Thanks in advance

Upvotes: 0

Views: 59

Answers (2)

Alexandr
Alexandr

Reputation: 1460

You need to use your code, AFTER you are generated your divs. So you need to put <script> after loop generation or on document ready event.
Try following:

$(function()
{
        var $el = $("#div"+ $("#counter").val() +" input");
        //or you can use alert($el.length) to see if $el created.
        if ($el.length)
        {
           var id =  $el.attr('id');
        }

});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You missed the space before input, try this:

$("#div" + $("#counter").val() + " input").attr('id')

Upvotes: 1

Related Questions