2

I'm trying to dynamically calculate the total of an order using Django/Python and Javascript.

I'm using radio buttons with pre-defined values, which are displayed based upon which products are currently in stock and what other items support.

Example: motherboard that supports a max of 8gb of ram would display 4 radio buttons, 2gb, 4gb, 6gb, and 8gb

this is what my template for this input field looks like so far:

{% for ram in orderData.ram %}

<div class="field"><input id="ram{{forloop.counter}}" name="ram" type="radio" class="ram" value="{{ ram.id }}" price="{{ ram.price }}"{% ifequal ram.default 1 %} checked {% endifequal %}/><label>{{ ram.title }}</label> {% ifnotequal ram.price 0 %}<span class="price">add ${{ ram.price }}</span>{% endifnotequal %}</div>

{% endfor %}

i was originally planning on using a "price" attribute to store the price, but as of right now, whenever I select a different radio button, it only displays the price for the first input. Is there any way around this? I tried adding a unique ID field, but it still only grabs the first radio value.. which is making that virtually useless.

javascript/jquery:

$("input").change(function(){

var id = $(".ram").attr("id");
alert(id);
alert($("#"+id).attr("price"));


});

I've been working on trying to figure out a way around this for the better part of two hours and I'm stumped. Any help would be much appreciated.

** Edit **

To summarize the issue.. how can I only get the price for the radio button that is currently selected.

Chris
  • 673
  • 1
  • 10
  • 28

2 Answers2

2

var id = $(".ram") is an array of all the items with this class name.

This will loop through them all.

$(".ram").each(function() {
     alert($(this).attr("price"))
})

You can address them individually using an index like this:

for(var x=0;x<$(".ram").length;x++) {
    alert($(".ram").eq(x))
}

The selected radio button will be:

$('.ram:checked').attr("price")
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
2

Here you go:

$(function() {
    $('input[name="ram"]').change(function() {
        var id = $(this).val(); // currently selected value
        var price = $('input[name="ram"][value="'+id+'"]').attr('price');
    });
});
Finbarr
  • 31,350
  • 13
  • 63
  • 94