Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally render form fields based on user selection

The application has several types of properties, such as house, apartment, shop, land, farm, etc..

First, the User selects the type of property in a select field and based on the type of property selected, i need to render the rest of the form with only the specific features of each type of property. I'm using nested attributes with simple_form.

The properties are registered in one table that contains general attributes and a string column with the property type. The other attributes are in separate tables: structural attributes (area, size of the ground, floors, rooms, etc.), address (state, city, district), and specific characteristics (name of condominium, position in the building, etc.)..

I found something similar using the function .change () in jQuery. But I could not make it work in my rails 3 app. Should i use case - when, to render each type form based on the selected value? Should i use partials for each especific form?

How can i, based on the value of the property-type selected in form, render the rest of the fields for each specific type of property?

Thanks in advance and sorry for the horrible English.

like image 987
Rômulo Melo Avatar asked Jan 17 '23 18:01

Rômulo Melo


1 Answers

Personally I would render all the forms at once, and hide them with css. Then using the jQuery .change() function check to see which property type is selected, and use jQuery to unhide the appropriate form sections. This may be a little more costly to initially load the page, but it will probably be quicker/easier than polling the server to get the appropriate form fields to render after the user selection.

Some pseudo code for this would look like:

Forms:

<select id="property_type">
  <option value='type_1'>Type 1</option>
  <option value='type_2'>Type 2</option>
</select>

<div id='type_1' class='type_forms'>
  <form></form>
</div>

<div id='type_2' class='type_forms'>
  <form></form>
</div>

JS:

$('select#property_type').bind('change', function() {
  $('.type_forms').hide();
  $('.type_forms input').attr('disabled', true);
  var selection = $(this).val();
  $('#' + selection).show();
  $('#' + selection + ' input').attr('disabled', false);
}).change();

This can definitely be approved upon, but hopefully it helps to illustrate the idea.

If you need to poll the server you could though using an ajax call within the .change() function to inform a controller action of the user select, and then have it render an appropriate partial to display in the ajax callback.

like image 129
JDutil Avatar answered Jan 31 '23 09:01

JDutil