I'm new to Rails so sorry for the extremely basic question. I'm trying to store the value of a jQuery UI Slider in my database when a form is submitted. For other elements such as a text_area this can be done by
<%= f.text_area :my_score %>
or for a date with datepicker (using the jQuery Datepicker Rails plugin): <%= f.datepicker :my_date %>
. However, I am having trouble finding a plugin for the slider and from my research it seems the best way is through the use of hidden_field. However, I don't know the correct notation for taking the value of the slider and correctly passing it to the form. Any help would be greatly appreciated.
<div id="slider"></div>
<input type="hidden" id="hidden"/>
<%= f.hidden_field :my_score, :value => (what goes here?) %>
Javascript for the slider:
<script>
$(function() {
$( "#slider" ).slider({
value:100,
min: 5,
max: 200,
step: 5,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
},
change: function(event, ui) {
$('#hidden').attr('value', ui.value);
}
});
$( "#amount" ).val( $( "#slider" ).slider( "value" ) );
});
</script>
Your view code should just be:
<div id="slider"></div>
<%= f.hidden_field :my_score %>
You already have a hidden field, don't need the second one. Also no need for a value, rails will put one in if there is one already there (ie. on edit).
As for your javascript, you would have the change event like this:
change: function(event, ui) {
$('input#model_name_my_score').val(ui.value);
}
I don't know the exact ID your hidden field will have, but it's usually model_name_field_name. You will need to check that.
The last thing you will need to do is set your slider to the right value on page load (assuming there is an edit version of your form and an existing value might be there).
$( "#slider" ).slider({
value: $('input#model_name_my_score').val(),
If you want 100 to be the default when creating a new object, then you should set that 100 in the model or where ever you like to set defaults, that way rails will pre-populate the hidden field with that value on a "new" form. You might check out a gem like https://github.com/FooBarWidget/default_value_for if you don't have a way to handle default values yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With