Vereonix
Vereonix

Reputation: 1414

Pass a PHP variable from a loop via an onclick

This may have been answered elsewhere but I couldn't find a question which fit my circumstances.

I have a site page which out puts in DIVs records from a database, this the same DIV looped. In this DIV I have a button which brings up a modal box. This modal DIV however is not coded within the looped DIV.

I need the modal box to be able to get the ID of the record for the data which the looped DIV is showing.

The button is:

<a href = "javascript:void(0)"onclick = "document.getElementById('light2').style.display='block';document.getElementById('fade').style.display='block'">
                                <div class= "obutton feature2">Reserve Book</div>
                                </a> 

I assume I'll need to use java script somehow, but I don't know how to use it in this manner.

Ideally using some sort of form $_POST would be easiest with the form button having the set value of the $row->ID, but I can't make a form button also a can I?

Sorry for the possibly silly question, as I've said I've found similar things asked, but always find it hard to understand the full workings on other peoples scenarios as opposed to my own.

All help appreciated -Tom

Upvotes: 1

Views: 1783

Answers (1)

Mechame
Mechame

Reputation: 90

I think the key to your answer is understanding how JS (and jQuery) uses this. When a function is called, the caller is almost always passed as the this variable. For example:

<button data-id="1234" onclick="runThisFunction()" value="run" />
<script>
function runThisFunction() {
    //Do Stuff
    var data_id = this.data('id');
};
</script>

In the above code, this contains the button that was clicked on. You can get lots of information from the this variable. In jQuery, you can even get to siblings, parents, or children in the DOM.

Here is an example solution to your question:

http://jsfiddle.net/yr6ds/1/

Here is a more elegant solution:

http://jsfiddle.net/yr6ds/2/

Upvotes: 3

Related Questions