I have the following form in my edit.html.erb page
<%= form_for(@device) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :description %>
<%= f.text_area :description, :rows => "5" %>
<%= f.label :device_identifier %>
<%= f.text_field :device_identifier, :value => @device.device_identifier, :readonly => true, :class => "d-id", :id => "deviceIDfield" %>
<%= button_tag "New device identifier", :id => "deviceIDbutton", :class => "btn btn-small btn-inverse", :type => "button" %>
<%= f.submit "Save changes", :class => "btn btn-large btn-primary", :id => "white" %>
<% end %>
When clicking on the "New device identifier" I want the :device_identifier field to regenerate its value which is currently set through the Ruby method SecureRandom.urlsafe_base64. This simply generates a random base64 encoded string. I have been trying to do this through jQuery however am having trouble as I am new to both Ruby on Rails and JQuery.
I set up a file called shared.js.erb which is located in my javascripts directory. In here I have the following code...
$(document).ready(function(){
$('#deviceIDbutton').click(function () {
$("#deviceIDfield").val('<%= SecureRandom.urlsafe_base64 %>');
});
})
This works the first time I click the button (i.e. it updates the device_identifier field with a new string) however stops working after this. I assume this is because SecureRandom.urlsafe_base64 is being called once (when the document is ready..?) and not each time the button is clicked. Could someone please help me!, I've been banging my head over this for way too long.
I am quite unsure about a few things such as why I don't need to use :remote => true anywhere and if I were to use it where to put it?
Also, I am by no means sure that I have the right idea about where the jQuery should go and although it seems to work in the shared.js.erb file that I created, if some one could recommend a better/more natural way that would be great.
It's also worth mentioning that I have the same button in my new.html.erb file which I want to apply the same functionality.
Thanks a lot!
Ben