简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM