My app is based on Python 3.4 and Flask, but I need to use JavaScript to dynamically change the values of hidden fields. I am not familiar with JavaScript and I don't know why my code isn't working.
In one of my templates I have a very simple payment form that allows the user to select a single bundle of credits using radio buttons (I stripped out the CSS and form action):
<form>
<input id="amount" value="price_list.price1" type="radio" name="amount">
<input id="amount" value="price_list.price2" type="radio" name="amount">
<input id="amount" value="price_list.price3" type="radio" name="amount">
<input id="amount" value="price_list.price4" type="radio" name="amount">
<input id="item_name" type="hidden" name="item_name" value="">
<input id="item_description" type="hidden" name="item_description" value="">
<input id="custom_int1" type="hidden" name="custom_int1" value=0>
<input id="payment" type=submit value=Payment>
</form>
The "price_list.price1" fields refer to a dynamic price, set by the system. This changes hourly, but each of the entries point to a given number of credits.
Due to the requirements of the payment processor I use, I need to change three hidden fields depending on the selection made namely item_name, item_description and custom_int1 (which represents x number of credits bought).
I referenced the following answers:
- Dynamically Change Multiple Hidden Form Fields
- Setting a form variable value before submitting
- Jquery Onclick Change hidden parameter and submit
What I ended up with is an attempt to use jQuery to change the values. The code is as follows:
<script>
$("#amount").change(function () {
// Get a local reference to the JQuery-wrapped select and hidden field elements:
var sel = $(this);
var set_name = $("input[name='item_name']");
var set_description = $("input[name='item_description']");
var set_creds = $("input[name='custom_int1']");
// Get the selected option:
var opt = sel.children("[value='" + sel.val() + "']:first");
// Set the values
if (opt.value=={{ price_list.price1 }}) {
set_name.value = '1 Credit';
set_description.value = '1 Credit';
set_creds.value = 1;
} else if (opt.value=={{ price_list.price5 }}) {
set_name.value = '5 Credits';
set_description.value = '5 Credits';
document.getElementById('custom_int1').value = 5;
} else if (opt.value=={{ price_list.price10 }}) {
set_name.value = '10 Credits';
set_description.value = '10 Credits';
set_creds.value = 10;
} else if (opt.value=={{ price_list.price25 }}) {
set_name.value = '25 Credit';
set_description.value = '25 Credit';
set_creds.value = 25;
} else if (get_amount.value=={{ price_list.price50 }}) {
set_name.value = '50 Credits';
set_description.value = '50 Credits';
set_creds.value = 50;
};
});
</script>
I added the script at the bottom of my template right before the <body>
tag.
The script does not work to change the hidden fields at all. Any and all help would be greatly appreciated.