user3484925
user3484925

Reputation: 61

can't get data attribute with jquery

I am trying to retrieve data-cost("#packages") and append it to #form next to Ticket-price. I am not getting any errors in console. I can't seen to understand what went wrong.

JS:

<script src="jquery-1.11.2.js"></script>
<script>
    $(document).ready(function()
      {
        var price=$("#packages").data("cost");
        var amount=$("<span>"+price+"</span>");
        $("#form").next().next().append(amount);

    });
</script>

HTML:

<div id="packages">
    <h2><u>Tourism Packages:</u></h2>
     <ul>
        <li data-name="Southern Travels">Travels Name:  Southern Travels</li>
        <li data-cost="2000">Cost per person:  2000</li>
        <li>Duration:  3 days & 4 nights</li>
     </ul>
</div>

<div id="form">
    <label>Number of persons </label>
    <input id="input"type="text"/ autofocus>
    <p id="ticket-price">Ticket Price</p>
</div>

Upvotes: 1

Views: 527

Answers (3)

amazedinc
amazedinc

Reputation: 418

You need to look for your data attribute by name - and look at the LI's.

You also need to build your html string and append it properly to the #ticket-price

WOKING EXAMPLE (FIDDLE): http://jsfiddle.net/ojLo8ojz/

JS:

    $(document).ready(function(){
        var price = $("#packages li[data-cost]").attr("data-cost");
        var amount = "<span> "+price+"</span>";
        $("#ticket-price").append(amount);
    });

Upvotes: 0

frogatto
frogatto

Reputation: 29285

$(document).ready(function() {

    // Targeting 2nd li element inside #packages
    var price=$("#packages li").eq(2).data("cost");

    // create a span element with text 'price'
    var amount=$("<span>"+price+"</span>");

    // append as last child of the form
    $("#form").append(amount);
});

Upvotes: 0

JCOC611
JCOC611

Reputation: 19759

For this to work as it is, you must edit your HTML as following:

<div id="packages" data-name="Southern Travels" data-cost="2000">
    <h2><u>Tourism Packages:</u></h2>
     <ul>
        <li>Travels Name:  Southern Travels</li>
        <li>Cost per person:  2000</li>
        <li>Duration:  3 days & 4 nights</li>
     </ul>
</div>

Either that, or access the data properties of the <li> elements instead of the div#packages (i.e #packages ul li instead of #packages)

Upvotes: 2

Related Questions