I need to collect the value of the radio button into the database, but I also need another value collected based on the radio button selected. The values will rarely change so having a front-end solution seems the way to go. The code below works as it should, but I feel the jQuery functions can be combined and dried out considerably. Is there a way I can combine the four functions into a single function?
My form data
...
<%= f.radio_button :plaque_size, '16" x 8"' %> 16" x 8" / $1,800 Donation
<%= f.radio_button :plaque_size, '12" x 8"' %> 12" x 8" / $1,500 Donation
<%= f.radio_button :plaque_size, '8" x 8"' %> 8" x 8" / $1,200 Donation
<%= f.text_field :plaque_cost, class: 'hidden' %>
...
jQuery
$(function () {
$('#plaqueorder_plaque_size_16_x_8').change(plaque_size_16_x_8);
$('#plaqueorder_plaque_size_12_x_8').change(plaque_size_12_x_8);
$('#plaqueorder_plaque_size_8_x_8').change(plaque_size_8_x_8)
});
function plaque_size_16_x_8() {
$('#plaque_cost').val('180000');
}
function plaque_size_12_x_8() {
$('#plaque_cost').val('120000');
}
function plaque_size_8_x_8() {
$('#plaque_cost').val('95000');
}
I would modifiy your html first with two goals...
Set a field for each radio button that will allow you to obtain the corresponding donation amount in your jQuery code. You can set a value
attribute, or a data-donation
attribute, etc.
Set a way to select all the radio buttons easily in jQuery. A class, for example.
I don't now rails, but I guess it has to be easy to do. The idea is that the html result looks similar to this...
<input type="radio" class="rbdonation" value="180000"...
<input type="radio" class="rbdonation" value="120000"...
<input type="radio" class="rbdonation" value="95000"...
Then, you can do what you want in one jQuery event function...
$('input.rbdonation').change(function() {
$('#plaque_cost').val(this.value);
});
Or if you need the value
field for other purpose, you can use the data-*
attribute...
HTML:
<input type="radio" class="rbdonation" data-donation="180000"...
<input type="radio" class="rbdonation" data-donation="120000"...
<input type="radio" class="rbdonation" data-donation="95000"...
JQUERY:
$('input.rbdonation').change(function() {
$('#plaque_cost').val($(this).data('donation'));
});
Why not just make one plaque_size function and pass in the value you want rather than converting? You'll habe just one function if you do:
function plaque_size (size) {
$('#plaque_cost').val (size);
}
and call it like so:
$('#plaqueorder_plaque_size_16_x_8').change(plaque_size ('180000'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.