2

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?

1
  • 2
    This depends greatly on your code and what you are trying to do, you can generate jQuery from php and insert the variables, you can use classes, you can use data attributes etc. but it all depends on the situation. Commented Aug 16, 2011 at 14:50

4 Answers 4

2

Use a class.

<div id='$id' class="myDiv" onclick='myfunction($id)' >

Then you can do this in jQuery:

$(".myDiv").each(function() {
    // write code here.
});
Sign up to request clarification or add additional context in comments.

Comments

1

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; ?>')" >

Comments

0

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'));
  });
});

2 Comments

Please explain this bit - '[id^="my_function_"]'
So that will let you search for ids beginning with my_function_ so in reference to your other question you could then use substr like: var id = $('[id^="my_function_"]').attr('id').substr(13);
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.