views:

45

answers:

3

I have a simple

$.ajax({
 url: someUrl, 
 method: 'get',
 dataType: 'html',
 success: function(data) { 
            $('#someId').append($(data));
          } 
 });

The problem is I can't find elements simply within the returned data. If there's an input with id="myInput" I can't get it with $('#myInput') or $('input[id=myInput]'). I CAN find it with:

$('input').each(function(i,e){ if($(e).attr('id') == 'myInput'){ doStuff(e); } });

But who wants to do that each time? I saw this question but the solutions provided didn't work for me. In addition to what's up there I've tried

$('#someId').html(data);
$(data).appendTo($('#someId'));

and I'm using jQuery 1.4.2. Thoughts, suggestions?

+2  A: 

The only cause of this I can think of is that your HTML syntax is malformed somewhere. Try taking out chunks of code in front of and after your myInput element and keep doing so until it functions as expected. Then slowly put pieces back in until you can identify exactly where the issue is.

Spencer Ruport
Good call. I wasn't the one composing the HTML and didn't realize the id's were invalid. The ids contained parentheses for some reason and JQuery seems unwilling to find by id in that case. So when I did a few test runs with HTML containing only a div or two it was fine until I put a paren in the id. Thanks for the suggestion.
Felix
+1  A: 

I think what you are trying to do is access a element in the DOM that you haven't yet attached to the DOM. untill you $(someElement).html(data) or append it somewhere, it's just a data return object and not yet part of the DOM.

also, consider using getJSON to get the data back as JSON (encode it as JSON on the remote end by putting it in an array in PHP and doing echo json_encode($array); then you can access each item by it's array name, as data.NAME and assign it to parts of your DOM.

FatherStorm
A: 

If you really need to do this (not sure why) then use .find on the returned data

so in your success function something like

success: function(data) { $(data).find("#inputId").doSomething(); $('#someId').append(data); }

FatherStorm is probably right, if you're doing an append, then just searching the whole dome using $("#inputId"), it probably just doesn't exist in the DOM yet.

brad