Skip to content

Instantly share code, notes, and snippets.

@calexandrepcjr
Created June 30, 2017 20:58
Show Gist options
  • Save calexandrepcjr/9bc73c1d637e0e07a19037986b68ed8f to your computer and use it in GitHub Desktop.
Save calexandrepcjr/9bc73c1d637e0e07a19037986b68ed8f to your computer and use it in GitHub Desktop.
A piece of code to help to change class in an row of elements like survey stars
/*
Code to add stars in a satisfaction survey, using font-awesome to change the look of the stars
HTML structure below:
<label class='fa fa-user-md'>
<span>Overall Satisfaction</span>
<span>
<label class="fa fa-star-o">
<input type="radio" name="satisfaction" value='0'>
</label>
<label class="fa fa-star-o">
<input type="radio" name="satisfaction" value='1'>
</label>
<label class="fa fa-star-o">
<input type="radio" name="satisfaction" value='2'>
</label>
<label class="fa fa-star-o">
<input type="radio" name="satisfaction" value='3'>
</label>
<label class="fa fa-star-o">
<input type="radio" name="satisfaction" value='4'>
</label>
</span>
</label>
*/
Array.prototype.forEach.call(inputs, function(el) {
el.addEventListener('click', function(){
//convert the HTMLCollection Label to JS array
var stars = [].slice.call(this.parentNode.parentNode.getElementsByTagName('label'));
var totalStars = stars.length;
var currentElementPosition = this.value;
for (i = 0; i < totalStars; i++) {
if (i <= currentElementPosition) {
stars[i].className = 'fa fa-star';
} else {
stars[i].className = 'fa fa-star-o';
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment