I have the variable $id in a loop which is the div id, so the div id is always changing. I know with javascript it's done like this.
<div id='$id' onclick='myfunction($id)' >
How do i use jquery to get variables i don't know their id?
I have the variable $id in a loop which is the div id, so the div id is always changing. I know with javascript it's done like this.
<div id='$id' onclick='myfunction($id)' >
How do i use jquery to get variables i don't know their id?
You should assign a class to those divs, and use jQuery to loop through all of the elements with that class:
$( ".your_div_class" ).each( function() { ... });
Also, you will need to output the PHP variables appropriately:
<div id="<?php echo $id; ?>" onclick="myfunction('<?php echo $id; ?>')" >
IF youre using jquery there is no real reason (other than some edge cases) to use the event handler attributes on the element like onclick. You should do everything unobtrusively. For example:
HTML:
<div id="<?php echo $id; ?>" class="some_class">
JS:
$.ready(function(){
$('.some_class').click(function(){
myFunction($(this).attr('id'));
});
});
Or lets say you ids conform to a certain format like my_function_10, then you can use attribute selectors:
<div id="my_function_<?php echo $id; ?>">
Then you can do:
$.ready(function(){
$('[id^="my_function_"]').click(function(){
myFunction($(this).attr('id'));
});
});
my_function_ so in reference to your other question you could then use substr like: var id = $('[id^="my_function_"]').attr('id').substr(13);If you really need to use inline event handlers you can always use onclick="myfunction(this.id);" to pass the ID. Or even better, onclick="myfunction.call(this);" so this points to the element inside the function.
But since you have jQuery available, there's no good reason to write onsomething a single time!