Skip to content Skip to sidebar Skip to footer

How To Use Html Id In A Ruby If Statement Condition

I'm trying to render a form depending on which checkbox has been ticked. I want to use an if statement with the checkbox's id in the condition, but rails is throwing up an error 'u

Solution 1:

Rails doesn't know that you are trying to reference the id field of the DOM objects because that's not something it's looking for. The reason you are getting that specific error is because ruby is looking at tab1.checked? and saying "before I can call checked? I need to grab tab1 so i can call checked? on whatever kind of object tab1 is... Now, do I have a variable or method defined called tab1... No? Then I'm going to throw an error because as far as I know it's undefined". Basically, it's not Ruby's job to think about HTML element IDs (in this context).

If you want to pull information from the DOM you should use Javascript. There is a separation of concerns to understand here. Think of it as if you are telling Rails to render everything when the view loads, then conditionally showing and hiding the sections using Javascript events.

here is an example:

<inputtype='checkbox' id='foo' checked>
<label for='foo'>Foo Questions</label>

<inputtype='checkbox' id='bar'>
<label for='bar'>Bar Questions</label>

<%= form_for :my_model do |f| %>
   <%= f.input :foo_questions %>
   <%= f.input :bar_questions %>
   <%= f.submit 'submit me' %>
<%= end %>

And then in your related Javascript file something like...

$(document).ready(function() {
   var fooQuestions = $('#foo_questions');
   var barQuestions = $('#bar_questions');

   $('#foo').on('click', function() {
      fooQuestions.show();
      barQuestions.hide();
   });

   $('#bar').on('click', function() {
      fooQuestions.hide();
      barQuestions.show();
   });

});

Keep in mind that even if you hide one of your questions, the value of that hidden form field will still be submitted with the form. If you are trying to submit different data sets then there is a good chance you are trying to do too much with one model. Or, if you really want to make it work you could use Javascript to take the responses from text boxes outside the form, pull the value that is entered and set it to a hidden form element inside the form. But that might be beyond the scope, so I'll just point you to this article...

This appears to be a good post on how to use hidden inputs

Post a Comment for "How To Use Html Id In A Ruby If Statement Condition"