Uness Uness - 3 months ago 8
jQuery Question

Hiding elements when form (menu select choice is empty)

I got a menu select of ''subjects'' generated by a form, I want to hide some stuff in the twig while the user didn't choose anything from the menu select.
This is my form :

class CollapsideColleFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('colles', EntityType::class, array(
'class' => 'PACESColleBundle:Colle',
'attr' => array( 'class' => 'browser-default colles' ),
'choice_label' => 'nom',
'label' => false,
'group_by' => 'matiere',
'required' => true,
'placeholder' => 'Choisissez une colle' ));
}
}


The twig :

<fieldset style='display: inline; border: 2px solid deepskyblue;'>
<!-- Menu SELECT OF COLLES -->
<legend> Choix de la colle</legend> {{ form_widget(formColle.colles) }}




<!-- STUFF TO HIDE when the user didn't choose a ''colle'' -->
<!-- Note -->
<fieldset style='display: inline; border: 2px solid deepskyblue;'>
<legend> Note </legend>
</fieldset>

<!-- Classement -->
<fieldset style='display: inline; border: 2px solid deepskyblue;'>
<legend> Classement </legend>
</fieldset><br><br>

<!-- Moyenne -->
<fieldset style='display: inline; border: 2px solid deepskyblue;'>
<legend> Moyenne </legend>
</fieldset>

<!-- Médiane -->
<fieldset style='display: inline; border: 2px solid deepskyblue;'>
<legend> Médiane </legend>
</fieldset>

<!-- Major -->
<fieldset style='display: inline; border: 2px solid deepskyblue;'>
<legend> Major </legend>
</fieldset>

<!-- Minor -->
<fieldset style='display: inline; border: 2px solid deepskyblue;'>
<legend> Minor </legend>
</fieldset>


I am not very good with form I tried to give an Id to the form then with Javascript check if the menu select is empty but I don't know how to do it

Thank you in advance for any help you can give me

Answer

You could use jQuery to get the job done.

First of all, you must see the generated id for your elements. This is as simple as to right-click over them on your browser and select "Inspect". This will show you the DOM tree of the page with the node corresponding to the selected element highlighted.

Also, give a common CSS class to all items that you want to be able to hide.

Then you simply need to add a javascript code similar to:

$(document).ready(function(){
  $('#id-of-the-select-element').change(function(){
    if($(this).val())
    {
      $('.class-for-all-the-hiddable-elements').show();
    }
    else
    {
      $('.class-for-all-the-hiddable-elements').hide();
    }
  });
  $('#id-of-the-select-element').change();
});