Get value of selected field from a dropdown list

Posted by 47 on Stack Overflow See other posts from Stack Overflow or by 47
Published on 2010-06-13T16:54:36Z Indexed on 2010/06/13 18:52 UTC
Read the original article Hit count: 192

Filed under:
|
|

I have this class in my model:

class ServiceCharge(models.Model):
  name = models.CharField(max_length=30)
  amount = models.PositiveIntegerField()
  extends_membership = models.BooleanField(default=False)

  def __unicode__(self):
    return str(self.name)

What I want to have is in the form for charging users a service charge, when a charge is selected from the dropdown menu, the two values for amount and extends_membership are updated on the form depending on the selected charge.

My forms.py:

class vModelChoiceField(forms.ModelChoiceField):
  def label_from_instance(self, obj):
    return "%s" % obj.name

class PayServiceChargeForm(PaymentsForm):
    service_charge = vModelChoiceField(queryset=ServiceCharge.objects.all(), 
      empty_label="     ")

    class Meta(PaymentsForm.Meta):
      exclude = ('member', 'payment_type', 'transacted_by', 'description')

Then the form template:

<table border="0">
  <tr>
    <td><strong>{% trans "Service Charge" %}</strong></td>
    <td>{{ form.service_charge }}</td>
    <td><strong>{% trans "Extends Membership" %}</strong></td>
    <td>{{ form.extends_membership }}</td>
  </tr>
  <tr>
    <td valign="top"><strong>{% trans "Expiry Date" %}</strong></td>
    <td valign="top">{{ form.expiry_date }}</td>
    <td valign="top"><strong>{% trans "Amount" %}</strong></td>
    <td>{{ form.amount }}</td>
  </tr>
 </table>

I was trying out some jQuery but I got stuck after getting the currently selected charge:

<script type="text/javascript">
$(document).ready(function(){
    $("#id_service_charge").change(onSelectChange);
});

function onSelectChange(){
    var selected = $("#id_service_charge option:selected");     
    var output = "";
    if(selected.val() != 0){
        charge = selected.val();
        .... (update values) ....
    }
}
</script>

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about django