I am working on a five star rating system. There are five star icons. When an icon is clicked, I want to change the value of an input to whichever star is clicked(e.g. if the fourth star is clicked, the input will have a value of 4). My problem is that the click method that I apply to the newly created icon does not work at all. What am I doing wrong? Here is a jsFiddle to demonstrate.
html
<div class="rating" style="float: none;clear: both;">
<noscript>
<label class="radio-inline">
<input type="radio" name="stars" value="1" title="1 Star"> 1
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="2" title="2 Stars"> 2
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="3" title="3 Stars"> 3
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="4" title="4 Stars"> 4
</label>
<label class="radio-inline">
<input type="radio" name="stars" value="5" title="5 Stars"> 5
</label>
</noscript>
</div>
<input type="text" name="stars" value="" id="stars">
Javascript
$element = $('.rating');
$element.empty();
for (var i = 0; i < 5; i++) {
var occurrence = i + 1;
var newStar = $('<i class="fa fa-star-o" title="' + occurrence + ' stars" data-occurrence="' + occurrence + '"></i>');
newStar.on('click', function() {
$('#stars').val(occurrence + ' stars given.');
});
$element.append(newStar);
}
$element.each(function() {
var _parent = $(this);
var originalStars = _parent.html();
$(_parent).on('mouseover', 'i[class*="fa-star"]', function() {
var starOccurrence = $(this).prevAll().andSelf().length;
$(this).prevAll().andSelf().removeClass('fa-star-o').addClass('fa-star');
}).mouseout(function() {
$(_parent).html(originalStars);
});
});