1

I'm very new to Rails and even newer to JavaScript, so bear with me.

It seems like Rails is sending a JQuery object's constructor to my script, rather than the value of the variable I'm giving it.

_form.html.erb

.....
<%= skill_form.check_box { id: "strength_checkbox_#{skill.id}" } %>
<%= render partial: 'proficiency_selector', locals: {strength_id: skill.id} %>
<%= javascript_tag("toggle_proficiency(#{skill.id});") %>
.....

_proficiency_selector.html.erb

<div id="proficiency_selector_<%= strength_id %>">
......
</div>

toggle_proficiency.js

$(function toggle_proficiency (strength_id) {
  alert(strength_id);
  .....
});

The proper skill.id is shown when I render it in the form, but the JavaScript alert is printing out the following:

function ( selector, context ) {

    // The jQuery object is actually just the init constructor 'enhanced'
    // Need init if jQuery is called (just allow error to be thrown if not included)
    return new jQuery.fn.init( selector, context );
}

Any help is much appreciated.

6
  • Try <%= javascript_tag("toggle_proficiency(#{skill.id});") %>
    – Abhi
    Commented Jun 9, 2017 at 15:02
  • Same result but thanks for the cleaner code! Commented Jun 9, 2017 at 15:08
  • What is the type of strength_id you need in JS? Check if this helps: javascript_tag("toggle_proficiency('#{skill.id}');"). If you want it as integer only, then parse it in JS parseInt(strength_id).
    – Abhi
    Commented Jun 9, 2017 at 15:13
  • strength_id should be a string. Putting quotes around #{skill.id} returns [object Object] and performing parseInt(strength_id) returns NaN. Commented Jun 9, 2017 at 15:21
  • 1
    That does it! Thank you so much! Commented Jun 9, 2017 at 15:41

0

Your Answer

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

Browse other questions tagged or ask your own question.