mehran gh mehran gh - 1 month ago 6
Javascript Question

Passing data id from a php loop to jquery

I am using PHP

foreach
loop to use create rating inputs:

<input id="input<?php echo $i ?>" data-id="<?php echo $i ?>" class="rating-loading">


The problem is
id="input"
should be unique for the jQuery function and I do not know how to pass this data id to the jQuery, I tried to make it something like this:

$(document).on('ready', function(){
$('#input'+id).rating({
//my function
});
});


However it is not working. If on top I make
id="input1"
and in the script I add
var id = 1;
it is working only for my first inputs inside loop, but I'm not sure how to pass this
data-id
to the jQuery. I even tried:

$(document).on('ready', function(){
$(this).attr('data-id').rating({
//my function
});
});


However this is also not working. Please help me.

Answer

Don't use incremental id attributes; they quickly become a pain to maintain. Use a common class instead. Your inputs already have a .rating-loading class, so we can use that:

<input data-id="<?php echo $i ?>" class="rating-loading">
$('.rating-loading').rating({
    //my function
});