How to modify an input that is inserted after page load (via AJAX)

I have a page that uses ajax to load form inputs into a div after the page loads. I need to be able to apply the autocomplete plugin to these inputs but obviously I have to do this after they are injected since they aren’t there on page load. Trouble is that for some reason I cant seem to get jQuery to match these injected elements no matter what I do.

so here is some code…


function moveRight(passedLI)
	{
		var mycontainer = $("#rightColumn");
		$.get("RightColumnAJAX.cfm", {id: $(passedLI).attr("id")}, function(data){
					data = $.trim(data)
					$(data).appendTo(mycontainer);
		});
		$('.jobCode').autocomplete({
			serviceUrl: 'jobCodeSearch_AJAX.cfm',
			minChars: 3});
	}

This is the function that is called which grabs the input and drops it into my div.

The inputs that are returned via AJAX have a class of jobCode so you can see above that I am trying to match the element with $(‘.jobCode’) but it just wont match the element. as a a matter of fact if I put a alert(‘matches: ’ + $(’.jobCode’).length); it tells me that it is nto matching any elements.

So how can I match these injected elements and manipulate them (apply the autocomplete plugin)?

I think what you are looking for is at http://api.jquery.com/on/.

The problem is that ajax requests are done asynchronously, so you code calls the autocomplete plugin before the new content has been returned and inserted into the page. Moving the call inside the $.get success callback should solve the problem:

$.get("RightColumnAJAX.cfm", {id: $(passedLI).attr("id")}, function(data){
    data = $.trim(data);
    $(data).appendTo(mycontainer);
    $('.jobCode').autocomplete({ serviceUrl: 'jobCodeSearch_AJAX.cfm', minChars: 3});
});

[QUOTE=fretburner;5542659]The problem is that ajax requests are done asynchronously, so you code calls the autocomplete plugin before the new content has been returned and inserted into the page. Moving the call inside the $.get success callback should solve the problem:
/QUOTE]

fretburner - I initially had the autocomplete call inside the $.get success callback - but that didn’t seem to work either. I was wondering if it might have been a timing issue because putting it on the line after the appendTo statment, maybe the appendTo action hasn’t finished yet. but I don’t think there is a callback function in appendTo, is there?

Thanks for the reply - I actually tried using the on function but didn’t have any luck with that.
I tried putting the following in my document ready…


$('#rightColumn').on('change', '.jobCode', function(){
     alert('matched: ' + $('.jobCode').length);
});

#rightCOlumn is the id of the div that my AJAX content is getting inserted into. I just wanted to see if it would match the element so I put an alert in there to display the number of matches for .jobcode and it didnt even get triggered. no alert at all.

am I misunderstanding the on function?

No, as far as I know appendTo is synchronous so it shouldn’t cause a problem. Could you share the HTML of the relevant section of your page, showing the additional content inserted?

sure… the content returned from the AJAX is as follows:


<div id="82">
        <strong>Meditech - Facility <a href="#" onclick="$(this).parent().parent().remove(); return false;"><i class="icon-remove"></i></a></strong><br>
         

        Document exception menu request:<br>

             
                <input type="text" name="question_82_9"><br>
            Job Code:<br>

            
                <input type="text" name="question_82_11" class="jobCode" value="9127"><br>
            

        <input type="hidden" name="AppID_82" value="82">
        <input type="hidden" name="AppName_82" value="Meditech - Facility">
        <label>Comments</label>
        <input type="text" class="span3" name="Comment_82"><br>
        <label class="radio inline">
            <input type="radio" name="Status_82" id="Status_82" value="Add">
            Add
        </label>
        <label class="radio inline">
            <input type="radio" name="Status_82" id="Status_82" value="Modify">
            Modify
        </label>
        <label class="radio inline">
            <input type="radio" name="Status_82" id="Status_82" value="Delete">
            Delete
        </label>
        <hr/>
    </div>

Ok I tried modifying my on function a bit so now it reads:


$('body').on('change', '#rightColumn', function(){
   			alert('matched: ' + $('.jobCode').length);
		});

So this is basically saying when the onChange event is fired for the #rightColumn div, display an alert.

but apparently a div does not trigger an onchange when its contents change because this isnt working.

to test I tried using a click handler and that works - it displays the alert when i click on the right column. So If I cant use the change event for the #rightColumn div, what event do i use for when the AJAX content is added?

bdee1, what do you get in your browser console if you do this?

$.get("RightColumnAJAX.cfm", {id: $(passedLI).attr("id")}, function(data){
    data = $.trim(data);
    $(data).appendTo(mycontainer);
    console.log( $('.jobCode') );
});

I got it working with the on function - woo hoo!!

here is the code I used:


$('body').on('change', '#rightColumn', function(){
   			//alert('matched: ' + $('.jobCode').length);
   			$('.jobCode').autocomplete({
						serviceUrl: 'jobCodeSearch_AJAX.cfm',
						minChars: 2,
						onSelect: function(suggestion) {
							alert('chosen: ' + suggestion.data);
						}
					});
		});

SO i wound up attaching the change event to the body element with a #rightColumn filter. the trick was that I had to manually trigger the change event (container.change()) after I add the AJAX content. like this:


function moveRight(passedLI)
	{
		var mycontainer = $("#rightColumn");
		$.get("RightColumnAJAX.cfm", {id: $(passedLI).attr("id")}, function(data){
					data = $.trim(data)
					$(data).appendTo(mycontainer);
					mycontainer.change();
					
		});

	}

thank you both for you assistance!!

Ok so I am almost there. I was able to attache the autocomplete plugin to the matched inputs and when the user types in the box, the autocomplete results pop up. but when the user clicks on one of the results, nothing happens. the value is not populated into the text box. whats interesting is that if I use the arrow keys and the tab key to select a result it works perfectly. It just doesn’t see the click action.

any ideas on this one?