Afonso Brandão
Afonso Brandão

Reputation: 1

Problem with JS and whitespace - Ruby on Rails and JS

I have a huge problem and don't know how to handle it. Look at the code below:

<div class="input-control row">
  <% ["Oneword", "With whitespace"].each_with_index do |answer, index| %>
    <%= label_tag "q7_#{index}", answer, class: "btn btn-reply question7", data: { "scroll-nav": "8", "question": "question_7", "answer": answer } do %>
      <%= radio_button_tag :question_7, answer, false, id: "q7_#{index}", class: "toggle" %>
      <%= answer %>
    <% end %>
  <% end %>
</div>

So, this is a Rails project and i have to get that answer when it's clicked and for that i code some JS right here (The form radio don't get true because of Scroolit that have e.preventDefault(); and I have several questions)

$('body').on('click','[data-scroll-nav]', function(e){
  var question = $(e.target).attr('data-question');
  var answer = $(e.target).attr('data-answer');

  if(question && answer) {
    console.log($('input:radio[name=' + question + ']').filter('[value=' + answer + ']').prop('checked', true));
  }
  e.preventDefault();
  doScroll(e);
});

With the 0 index word it works, but with 1 index it does not work, and debugging it I think it's because of whitespace. How can i handle this?

Upvotes: 0

Views: 32

Answers (1)

arieljuod
arieljuod

Reputation: 15838

I might be wrong, but I think you need to wrap question and answer in quotes for the selectors:

$('input:radio[name="' + question + '"]').filter('[value="' + answer + '"]')

Notice the " added around the variable parts.

Upvotes: 2

Related Questions