Hide a Div according to a field on your App Rails

Recently in a project I needed to hide a field and its label according to a value from another field. To achieve this dynamically, I used the Jquery of Javascript library.

That’s what we’re going to get !

hide a div dynamically: result

I take this opportunity to introduce and use a tool called Webpacker for managing Javascript dependencies with the yarn package manager. Webpack is a bundler module that takes the modules with their dependencies and generates static assets that can be used on the browser since version 5.1 of Rails. The bundler module allows you to group all our javascript, css and html files into one module.

Hide a Div according to a field: Here we go !

create a new project with the name of your choice, here “hide_a_div_jquery” by specifying the use of a PostgreSQL database

$ rails new masquer_une_div_jquery --webpack -d postgresql --skip-sprockets
$ cd masquer_une_div_dynamiquement
$ spring stop
$ rails generate controller properties
$ rails generate model Property properties_type:string floor:integer $ git add .
$ git commit -m "First commit"
$ hub create
$ git push origin master 

Create the table and migrate your data.

 $ rails db:create && rails db:migrate 

Add the gems,’simple_form‘ to your Gemfile

Simple_form will be used to build our form

# Gemfile 
# [...] 
gem 'simple_form' gem "turbolinks", "~> 5.0.0", require: false
# [...] 

Install the gems and finalize the installation of ‘simple_form‘.

$ bundle install
$ rails generate simple_form:install --bootstrap 

Edit the routes.rb file from /config/

# config/routes.rb
Rails.application.routes.draw do
 root 'properties#new'
 resources :properties, only: [:new, :create, :show]
end 

Replace javascript and stylesheet tags in your application.html.erb

# app/views/layouts/application.html.erb
# [...]
<head>     
 <%= javascript_pack_tag 'application' %>
 <%= stylesheet_pack_tag 'application' %>
</head>
# [...] 

Add the code for our controller in app/controllers/properties_controller.rb

# app/controllers/properties_controller.rb 
class PropertiesController < ApplicationController   
def new     
 @property = Property.new   
end   

def create
 @property = Property.new(property_params)
 if @property.save
  redirect_to property_url(@property)
 else
  redirect_to root
 end
end

def show
 @property = Property.find(params[:id])
end   

private
def property_params
 params.require(:property).permit(:properties_type, :floor)
 end
end 

Let’s continue to prepare our environment via webpacker

Bootstrap V4 and its dependencies

Install the latest version of Bootstrapv4, at the time of this tutorial it was 4.1.1 with its jquery and popper.js dependencies

You can check the latest version using the “yarn info bootstrap” command

 $ yarn add [email protected] jquery popper.js

Create the css folder in app/javascript/packs/ and add the file application.scss

/* app/javascript/packs/application.scss */
@import "~bootstrap/scss/bootstrap";
@import "index.scss"; 

Add bootstrap to the application.js file from the app/javascript/packs/ folder

 // app/javascript/packs/application.js 
  // bootstrap
  import 'bootstrap';
  import 'css/application.scss';
  // jquery
  global.$ = jQuery; 

Jquery-ui

Install the latest version of Jquery-ui

$ yarn add jquery-ui 

Add Jquery-ui to our application.js file

// app/javascript/packs/application.js 
// #[...] 
// jquery-ui
import 'jquery-ui/themes/base/all.css';
require( "jquery-ui/ui/widgets/autocomplete" ); 

Turbolinks

Add the latest version of Turbolinks

$ yarn add turbolinks 

Add Turbolinks to our application.js file

// app/javascript/packs/application.js 
// #[...]
// Turbolinks
var Turbolinks = require("turbolinks")
Turbolinks.start() 

To finish with our tools via webpack, add the code below in environment.js

// config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')

// Add an additional plugin of your choosing : ProvidePlugin environment.plugins.prepend(
 'Provide',
  new webpack.ProvidePlugin({
   $: 'jquery',
   jQuery: 'jquery',
   jquery: 'jquery',
   'window.Tether': 'tether',
    Popper: ['popper.js', 'default'],
  }) 
)

module.exports = environment 

Let’s add a little style !

Create an index.scss file in app/javascript/packs/ to center our elements using Flexbox

To know how the Flexbox system works, click HERE

/* app/javascript/css/index.scss */ 
.box {
 display: flex;
 justify-content: center;
 align-items: center;
 flex-direction: column;
 text-align: center;
} 

Edit the file new.html.erb from app/views/properties/ and add the code for our form

 <!-- app/views/properties/new.html.erb  -->
<div class="box">
 <h1>Masquer une Div en fonction d’un champ en Javascript et CSS</h1>
 <%= simple_form_for @property, method: :post do |f| %>
 <%= f.input :properties_type, placeholder: "Entrez votre type d'habitation", label: 'Appartement ou maison' %>
 <div id="hide_floor">
  <%= f.input :floor, collection: 0..10, selected: 0, placeholder: "N° étage", label: "Si c'est un appartement, Quel étage ?" %>
 </div>
 <%= f.button :submit, 'Ajouter', class: "btn btn-primary" %>
 <% end %>
</div> 

Hide a Div according to a field: the Jquery and the CSS

Return to the index.scss file in app/javascript/packs/ and add the display: none so that the field is not displayed on the page when it is loaded

/* app/javascript/css/index.scss */
/* [...] */
#hide_floor {   
             display: none; 
} 

Create a new file in app/assets/javascripts/packs/ named immo_type_autocomplete.js

This code will provide a drop-down list to the user. When he hits the button, he will have the choice to enter an apartment or a house

// app/assets/javascript/packs/immo_type_autocomplete.js 
$( document ).on('turbolinks:load', function() {
 return $("#property_properties_type").autocomplete({
  source: ["appartement", "maison"]
 });
});

Still in the same directory create the file floor_hide.js

The display = “none” will allow us to hide a div, the one with the id hide_floor

$( document ).on('turbolinks:load', function() {
 $('#property_properties_type').change(function() {
  if ($( this ).val() == 'appartement') {
   document.getElementById("hide_floor").style.display = "initial";
  }
  else {
   document.getElementById("hide_floor").style.display = "none";
  }
 });
});

All you have to do is launch your server from the command prompt: rails s and check the result from your browser

$ rails s

To see the result, click HERE

To see the sources, click HERE

Sources

https://github.com/rails/webpacker

https://getbootstrap.com/docs/4.0/getting-started/webpack/

https://github.com/plataformatec/simple_form

https://github.com/turbolinks/turbolinks

https://github.com/twbs/bootstrap

https://github.com/jquery/jquery

https://github.com/jquery/jquery-ui

signature Pierre-Christophe

No Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.