简体   繁体   中英

JavaScript code fails to render partials on form

I need help troubleshooting some JavaScript in my Rails 4 application. My goal is to improve user experience by only showing relevant form fields for different types of cardio exercises that a user may select.

For example, if a user selects "Cycling", I want a partial named "_cardio_time.erb" to show "distance," "predicted pace," and "duration" fields. If a user selects say "Jumping Jack", I want a partial named _cardio_sets to show "sets" and "reps" fields.

Here's my attempt at writing the JavaScript code:

$(document).ready(function() {
  $("#cardio_exercise_aerobic_training_list_id").change(function(e){
    e.preventDefault();
  $("<% if cardio_exercise.aerobic_training_list.category == 1 %>");
  $("<%= escape_javascript render(:partial => 'layouts/cardio_time.erb' %>").insertAfter('#read-cardio-exercise-description-text');
  $("<% else %>");
  $("<%= escape_javascript render(:partial => 'layouts/cardio_sets.erb' %>").insertAfter('#read-cardio-exercise-description-text');
  $("<% end %>");
  })    
});

The code does not generate any errors in the Firebug console, but when I select "Cycling" from the drop-down menu, the following text is rendered on the form:

<%= escape_javascript render(:partial => 'layouts/cardio_sets.erb' %><%= escape_javascript render(:partial => 'layouts/cardio_time.erb' %>

What am I doing wrong? I'm learning Rails and JavaScript. I would appreciate any help!

$(document).ready(function() {
    $("#cardio_exercise_aerobic_training_list_id").change(function(e){
        e.preventDefault();
        <% if cardio_exercise.aerobic_training_list.category == 1 %>
        $("<%= escape_javascript render(:partial => 'layouts/cardio_time.erb') %>").insertAfter('#read-cardio-exercise-description-text');
        <% else %>
        $("<%= escape_javascript render(:partial => 'layouts/cardio_sets.erb') %>").insertAfter('#read-cardio-exercise-description-text');
        <% end %>
    })    
});

See if removing jQuery wrapper for if/then/end sentences, and adding a missing bracket on the end of render solves the issue.

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