Question

I have a form with several inputs, for which I have live preview in Ruby on Rails app. Live preview works fine, until it comes to previewing form with existing record.

if my object is not created, I see something like this (note there is no "value" attribute)

<input class="deal_title" id="deal_title" name="deal[title]" type="text">

If I fill in the form and send it to the server, inputs "value"'s attributes are being assigned with user-entered values, so if I open the form source I see:

<input class="deal_title" id="deal_title" name="deal[title]" type="text" value="New offer">

I have a script to bind live preview:

  $("#new_deal input").keyup ->
    css_klass = $(this).attr("class")
    $(this).attr('value', $(this).val())
    inpt = $(this).val()
    $("." + css_klass + "_preview").html inpt

If I reproduce the same in JsFiddle, it works fine:

JsFiddle without "value"

JsFiddle with "value"

However in my Rails app, this only works in the first case (if no value is set). in the second case, nothing just happens and value stays the same. I copied inputs from my app, directly from the view. I use Rails 4 with turbolinks.

Was it helpful?

Solution

I found the answer myself!

This happens because rails applies custom ID to forms depending on action. If it is "New" action, then ID would be "new_object". If it is "Edit" action, then class would be "edit_object".

I applied custom class like:

<%= form_for(@deal, html: { "data-abide" => '', id: "deal_form"}, builder: SmartLabelFormBuilder) do |f| %>
...
<% end %>

and

$("#deal_form input").keyup ->
    css_klass = $(this).attr("class")
    $(this).attr('value', $(this).val())
    inpt = $(this).val()
    $("." + css_klass + "_preview").html inpt

And it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top