Danu Akbar Danu Akbar - 3 months ago 15
Javascript Question

Javascript One onclick Return Twice Result?

This is my code

<div class="rating">
@for ($i = 1; $i <= 5; $i++)
@if ($i <= ceil($rating[0]->average))
<i id="{{$i}}" style="cursor:pointer" class="fa fa-star rating"></i>
@else
<i id="{{$i}}" style="cursor:pointer" class="fa fa-star-o rating"></i>
@endif
@endfor
</div>


My Javascript

<script type="text/javascript">
$('.rating').click(function() {
var id = $(this).attr('id');
$.ajax({
url: "{{url('rating')}}",
type: "POST",
data: { id_artikel: "{{$artikel->artikel_id}}", _token: '{{ csrf_token() }}', value:id},
success: function(response){
alert('Bintang berhasil anda berikan!');
},
error: function(){
alert('Bintang gagal anda berikan!')
}
});
});

</script>


When i click i got twice result. The first give the correct 'id' and others give null. I was try to use unbind, but still give me twice result. I also try to make just only one and still give me twice result.

Answer

That's because you have two elements in the same DOM tree with a class rating.

I suggest renaming the class of your upmost <div> element to something else.

Comments