0

In my RoR application, user selects an option from a popup and the selected value is passed to hidden fields found in my parent form. The problem is when passing values containing html characters (e.g. <a href= ""> ) to the parent form.

In my popup, i have a link as follows which passes a value to the main form:

popup code:

<% @users.each do |user| %>
  <%= link_to_function "PassValue", "sendValue('"+ user.location+ "')" %>
  <% end %>

application.js:

  function sendValue(location){
    window.opener.document.getElementById('submission_user_attributes_location').value = location;
    }

The location value retrieved form the database can contain html chars like '', and this is where my sendValue function is not working.

Please can someone help me on this.

Many many thanks in advance for your help :)

1 Answer 1

1

Please do not use obstrusive javascript. Try rewriting this code using non obstrusive javascript and it will prevent you from running into more problems in the future. See this railscast for more info: http://railscasts.com/episodes/205-unobtrusive-javascript

This being said, you could fix your problem by encoding your user.location with URI.encode, or escape quotes manualy or use escape_javascript.

My favorite solution is escape_javascript. From the documentation:

escape_javascript - Escape carrier returns and single and double quotes for JavaScript segments.

# File actionpack/lib/action_view/helpers/javascript_helper.rb, line 50
def escape_javascript(javascript)
  if javascript
    javascript.gsub(/(\\|<\/|\r\n|[\n\r"'])/) { JS_ESCAPE_MAP[$1] }
  else
    ''
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

Yupee, it's working!! Thank you so much Marcgg, i finally opted for the escape_javascript method. But i will bear in mind your suggestions. Cheers..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.