I would like to display a comment section when the first radio button is checked, but I’m having trouble achieving it. Here’s my code:
I’ve tried the following to display the section and test the accompanying script:
<div id="commentaireDiv" style="display: none;">
<label for="commentaire">Commentaire :</label>
<textarea name="commentaire" id="commentaire" rows="4" cols="50"></textarea>
</div>
<script>
var boutonGeneral = document.getElementById('GENERAL');
var zoneCommentaireDiv = document.getElementById('commentaireDiv');
boutonGeneral.addEventListener('click', function() {
if (this.checked) {
zoneCommentaireDiv.style.display = 'block';
} else {
zoneCommentaireDiv.style.display = 'none';
}
});
</script>
This function show radio button :
<?php
$tab_list_action = Actions_Fondation::getTab_list_action();
foreach ($tab_list_action as $soustab) {
//on ne va pas afficher les dons ponctuels avec pourcentage
if ($soustab[2] == 'O') {
// si la collecte est en cours
if (($soustab[0] != 'DON_PROMO_2018') and ($soustab[0] != 'DON_PROMO_2018_NOG')) {
echo " <input type="radio" name="choix_action" id="$soustab[0]" value="$soustab[0]" required ";
if ($_var_choix_action == $soustab[0])
echo ' CHECKED';
echo "> <label class="" for="$soustab[0]">$soustab[1]</label>n<br>";
}
}
}
?>
The radio buttons are stored in an array, and I would like the section to be displayed when the first element is checked.
$tab_list_action[] = array("GENERAL", "Au développement de l'UTT en général", 'O');
I want to show comment section when first radio button is checked.
This is the radio button concerned :
$tab_list_action[] = array("GENERAL", "Au développement de l’UTT en général", ‘O’);
2
Answers
Something like this
I find it a good practice to use as many build-in-features as possible when it comes to HTML forms. First of all the fieldset element has a
disabled
attribute. This can be used for showing/hiding that part of the form.I also replaced all the IDs. Therefore the form can be reused (if you change the name of the form…). And now, it is really easy to pick out an form field or a fieldset.
The event listener will listen for all changes in the form. So, depending on the number of inputs etc. this can be changed, but for this simple case this can be fine. To find out if the radio button is selected/on you can just test of the value is "on" or if it is checked (I’m not sure if the radio button is appropriate here. If you have a "standalone" radio button it cannot be deselected — maybe a checkbox is better?).