Need some help passing jQuery UI Slider value to form using hidden_field in Ruby on Rails

I'm new to Rails, so sorry for the extremely simple question. I am trying to save a jQuery UI Slider value in my database when submitting a form. For other elements, such as text_area, this can be done using <%= f.text_area :my_score %> or for a date with datepicker ( using the jQuery Datepicker Rails plugin ): <%= f.datepicker :my_date %> . However, it’s hard for me to find a plugin for the slider, and from my research it seems that the best way is to use hidden_field. However, I do not know the correct notation for accepting the value of the slider and for passing it to the form correctly. 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 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> 
+4
source share
1 answer

Your view code should only be:

 <div id="slider"></div> <%= f.hidden_field :my_score %> 

You already have a hidden field, you don’t need a second one. There is also no need for a value, the rails will put one if it already exists (i.e. when editing).

As for your javascript, you will have a change event as follows:

 change: function(event, ui) { $('input#model_name_my_score').val(ui.value); } 

I do not know the exact identifier that your hidden field will have, but usually it is model_name_name_file_name. You will need to check this out.

The last thing you will need to do is set the slider to the desired value when loading the page (provided that there is a version for editing your form and the existing value may 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 must set 100 in the model or when you want to set the default values, so the rails will pre-fill the hidden field with this value on the "new" form. You can check the gem, for example https://github.com/FooBarWidget/default_value_for , if you do not already have a way to handle the default values.

+8
source

Source: https://habr.com/ru/post/1402081/


All Articles