événement sur une liste d'éléments

cas de boutons radio en forme d'étoiles

by ydelmas

HTML

<form action="http://azrael.sha.univ-poitiers.fr/~ydelmas/exemples/info-max.php">
    <div class="etoiles">
        <label>★<input type="radio" name="a" value="1" /></label><!--
        --><label>★<input type="radio" name="a" value="2" /></label><!--
        --><label>★<input type="radio" name="a" value="3" /></label><!--
        --><label>★<input type="radio" name="a" value="4"  /></label><!--
        --><label>★<input type="radio" name="a" value="5" /></label>
    </div>
    <button type="submit">envoyer</button>
</form>

CSS

.etoiles label { color: grey; }
/* CSS 2 */
.etoiles__etat-1 :first-child,
.etoiles__etat-2 :first-child,
.etoiles__etat-2 :first-child + * {color:#C90;}
/* CSS 3 */
.etoiles__etat-3 :nth-child(-n+3),
.etoiles__etat-4 :nth-child(-n+4),
.etoiles__etat-5 :nth-child(-n+5) {color:#C90;}
/* pour cacher les boutons radio */
.etoiles input[type=radio] { display: none; }

JavaScript

function changeEtoiles() {
    var n = this.value;
    this.parentNode.parentNode.className = 'etoiles etoiles__etat-' + n;
}

var liste = document.querySelectorAll('.etoiles input');

// méthode rapide (navigateurs récents)
liste.forEach(function(noeud){
    	noeud.addEventListener('change', changeEtoiles, true);
});

/* méthode classique
for(var i=0; i<liste.length; i++) {
    liste[i].addEventListener('change', changeEtoiles, true);
}
*/