Search code examples
javascriptruby-on-railsrubyrjs

rails rjs replacement and swap values


I'm trying to figure out how to use RJS to swap between two fields... i know how to replace the values but I can't seem to figure out how to read it.

Is it not possible to read values thru RJS? Only to replace?

<%= link_to_function "Swap" do |page| 
            #to_value = page[:currency_to].value
            page[:currency_from].value = to_value
            page[:currency_to].value = "test"
        end %>

http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper/JavaScriptGenerator/GeneratorMethods.html#M001664


Solution

  • I tested both of the following.

    <%= link_to_function "Swap", 'var tmp_frm = $("#currency_from").val();
                                  var tmp_to = $("#currency_to").val();
                                  $("#currency_from").val(tmp_to);
                                  $("#currency_to").val(tmp_frm);'%>
    

    or better yet

    <%= link_to_function "Swap", 'var tmp_frm = $("#currency_from").val();
                                  $("#currency_from").val($("#currency_to").val());
                                  $("#currency_to").val(tmp_frm);'%>
    

    depending on your html, you may need to remove the pound symbols

    <%= link_to_function "Swap", 'var tmp_frm = $("currency_from").value;
                                          var tmp_to = $("currency_to").value;
                                          $("currency_from").value = tmp_to;
                                          $("currency_to").value = tmp_frm;'%>