g-man1066 g-man1066 - 1 month ago 7
jQuery Question

I need to get the current content of an HTML element that has been changed by ajax

enter image description here

I have this bit of script that runs when I click a button. It reads an element on the page (In this case, with the class ".product-sku" and sends the innerText off to a PHP script that queries a database, etc. and returns a content block.

<script type="text/javascript">
jQuery(function($){
$(document).ready(function(){
$("#btnFindStore").click(function(){
sku_no = $(".product-sku").get(0).innerText;
$.post(
'DealerLinks.php',
{ sku: sku_no },
function( data ){ $('#output').replaceWith( data ); });
$('#altStores').modal('show');
});
});
});




The problem is other elements on the page (size options) are changing the data displayed in the
.product-sku
element (red shape near bottom of image) but once the above bit of script fires when button "B" is clicked, the
.innerText
does not change from the value that was read in the first time the
.click()
was fired.

In other words, even though the text displayed in the browser changes, the value of
.innerText
does not update and is not returned as the value of the variable when the function is triggered. It will return the correct value, but only once...after it has returned the value and the modal popover is closed, subsequent
.click()
s will return the value from the first time the
.click()
fired.

How can I get the "real" current value displayed in the
.product-sku
element when the
.click()
is fired instead of the "old"
innerText()
? value?

Answer

I'm not sure why/how, but changing script to the following seems to have done the trick.

<script type="text/javascript">
jQuery(function($){ 
    $("#btnFindStore").click(function(event){
        event.preventDefault();
        sku_no = $(".product-sku").html(); 
        $.post( 'dlinks.php', { sku: sku_no }, function( data ){  
            $('#output').html( data );  
        });
        $('#altStores').modal('show');
    }); 
});
</script>

I first tried changing the assignment line that gets the SKU value from the page: sku_no = $(".product-sku").html(); but doing so did not seem to alleviate the problem.

Then I stumbled across this: Setting the content of the modal popup behaves differently when using $('#output').replaceWith( data ); as opposed to $('#output').html( data );.

Here's a link that provides more information on .replaceWith(); and .html(); Once the script ran the first time, it was replacing the ID #output with HTML, and on subsequent clicks, there was no #output to replace...so it didn't.

Works nice now. Hope this helps someone else.