简体   繁体   中英

Display an input according to the value of a drop-down list symfony

im trying to display an input according to the value of a drop-down list with symfony

my select box

->add('specialite', ChoiceType::class, [
                'attr' => ['class' => 'form-control mb-3'],
                'label' => 'Speciality',
                'choices' => array(
                    'Select' => null,
                    'Nurses' => 'nurses',
                    'Doctors' => 'Doctors',
                    'Engineers' => 'Engineers',
                    'IT-Specialist' => 'IT-Specialist',
                    'Anesthetist technicians' => 'Anesthetist technicians',
                    'Others' => 'Others',
                ),
                'choice_attr' => [
                    'Select' => ['disabled'=>'disabled'],
                ]
                
            ])

when the user select others , another field it displayed to him , im trying also with this code

form type

    ->add('otherspec', TextType::class, [
        'attr' => ['class' => 'form-control mb-3'],
        'label' => null,
    ])

html.twig

<script>
let foo = document.getElementById("emplopyer_specialite");
let bar = document.getElementById("emplopyer_otherspec");

foo.addEventListener('change', (event) => {
    if (event.target.value === 'Others') {
          bar.style.display = 'none'; // Hide the element.

  } else {
        bar.style.display = 'inline'; // Show the element.

  }
});

</script>

My problem my problem is whene i select any value of the select box , the second field appear , however i want it appear when i select the value="other"

thanks

If you console.log your event.target.value, you can see '1', '2'... The offender is : 'Select' => null

Documentations says :

If there are choice values that are not scalar or the stringified representation is not unique Symfony will use incrementing integers as values. When the form gets submitted the correct values with the correct types will be assigned to the model.

So, if you want string as value, you have to set string in your Select key. Or you can change your js condition with 6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM