Search code examples
javascriptruby-on-railsrubyruby-on-rails-5

Saving additional field from dropdown


I m having list of relations, when I select Other, new fields shows AddOther, and when I enter Test into new field, in database i get stored Other, because it takes from the f.select. What should i do to save into database from new field when i choose Other from the list.

= f.select(:relationship, ['Father', 'Mother', "Sibling", "Children", "Friend", "Spouse", "Other"], {}, { :class => 'form-select  RelationshipSelect'  })
        fieldset class="form-group" style="display:none"
        input#AddOther.mt-4.form-control[type="text" style="display:none" placeholder="Enter other relationship"]

$('.RelationshipSelect').change(function() {
    var v;
    v = $(this).val();
    if (v == 'Other') {
        $('#AddOther').slideDown();
    } else {
        $('#AddOther').slideUp();
    }
});

I tried to add AddOther to f.select but no progress. Cant figure it out how to save AddOther into list to be able to save it as Father, Mother....


Solution

  • This feels risky, because the relationship will only be valid/available for one use. You will be prone to pick up lots of "dirty" data.

    That said, you could add jquery to monitor the 'change' event of AddOther, which would retrieve the value, add a new option to the select, set the value of the select to that value.

    $('#AddOther').on('change', function(){
      relationship = $(this).val();
      $('.RelationshipSelect').append("<option value=\"" + relationship + "\">" + relationship + "</option>").val(relationship);
      $(this).slideUp();
    });