Reputation: 3224
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?
Upvotes: 2
Views: 1414
Reputation: 60413
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'));
});
});
Upvotes: 0
Reputation: 318518
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!
Upvotes: 0
Reputation: 28906
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; ?>')" >
Upvotes: 1
Reputation: 62593
Use a class.
<div id='$id' class="myDiv" onclick='myfunction($id)' >
Then you can do this in jQuery:
$(".myDiv").each(function() {
// write code here.
});
Upvotes: 2