twan
twan

Reputation: 2659

Changing data-src value using jQuery not working

I have the following line of code:

tpj("#totalcostinclship").empty().append( "<span data-src='"+pricefinal+"' id='totalcostinclship'></span>" ).text(pricefinal);

It first empties the existing element and then appends the new element. pricefinal in this case contains 245 but when I inspect my HTML, this is what I see:

<span data-src="220" id="totalcostinclship">245</span>

The .text is applied but the data-src not at all. Why could that be? 220 is the value of the data-src on page load, so before any jQuery event is started.

Upvotes: 0

Views: 275

Answers (1)

Kirsten Phukon
Kirsten Phukon

Reputation: 314

var pricefinal = 245;
var tpj = $.noConflict();

tpj("#totalcostinclship").empty().append("<span data-src='" + pricefinal + "' id='totalcostinclship'></span>").text(pricefinal);
tpj("#totalcostinclship").attr('data-src',pricefinal);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="totalcostinclship"></div>

Add this line

tpj("#totalcostinclship").attr('data-src',pricefinal);

after your js. Like this ->

tpj("#totalcostinclship").empty().append( "<span data-src='"+pricefinal+"' id='totalcostinclship'></span>" ).text(pricefinal);
tpj("#totalcostinclship").attr('data-src',pricefinal);

Upvotes: 2

Related Questions