Search code examples
ruby-on-railsrubyruby-on-rails-4slim-lang

add checkbox content to text field


New to rails, also not great in english... I need some advice please.

I have a form with a non-exhaustive list of drugs. The user can select drugs with check-boxes. There is a check-box called "Other" which makes a text field appear (with a JS script). The content of this text field is saved in my database under the column :taken_drugs

Here is the code I got until now :

= form_for @quizz, :url => { :action => "create" } do |f|

h4 Which drugs did you take ?
h5 (You can answer more than one)
.field class="list-group"
  div class="list-group-item"
    = check_box("LSD", "yes")
    = label_tag 'LSD'
  div class="list-group-item"
    = check_box("Psilocybine", "yes")
    = label_tag 'Psilocybine (mushrooms)'
  div class="list-group-item"
    = check_box("DMT", "yes")
    = label_tag 'DMT (ayahuasca)'
  div class="list-group-item"
    = check_box("other", "other", {}, "yes", "no")
    = label_tag 'other'
    div id="disappear_consomme" style="display:none"
      p Which other drugs did you take ?
      = f.text_field :taken_drugs
    =f.submit

How can I have a result where I save to :taken_drugs the drugs that are checked AND the drugs that are added to the text field ?

Examples of what I need :

  • if the user check "LSD" and "DMT" I have "LSD DMT"
  • if the user check "LSD" and write "CANNABIS VALIUM" I have "LSD CANNABIS VALIUM"

Solution

  • You have two options, you can either catch this data in the front end with javascript or you can catch it in the back end with Ruby before it is posted to your database.

    The js way:

    var text = "";
    for (var i = 0; i < form.elements.length; i++ ) {
        if (form.elements[i].type == 'checkbox') {
            if (form.elements[i].checked == true) {
                text += form.elements[i].value + ' ';
            }
        }
    
    }
    

    Stick that in a function. Call it from your submit button with an onClick or onSubmit event handler.

    The ruby way would be handled in your rails controller create method and parsing through whatever you are passing up in your params hash.