0

I have a a grid of images which has it's HTML generated with PHP. Each image has an onclick() function, which has a PHP variable in the arguments. On the page that the HTML is on, I have a Javascript function which uses the arguments in the onclick(arg) function.

I've started to use jquery and I want to be able change this onclick() function into my jquery functions, while using the PHP arguments from the PHP page.

This is the code from the PHP file that generates the HTML, as you can see, there is an onclick function, which would have an argument that is a number:

Echo "<img src= '$link[Image_Link] . /133x100' id='$row[Item_Name]' title='$row[Item_Name]' class='clickableImage' alt='$just_name' onClick='addValue(". $credit_value .")' border=0 style='position: relative; top: 0; left: 0;'/>";

This is my Javascript function on the HTML page, it just changes some text on the page:

function addValue(credits){
    var value = document.getElementById("value").innerHTML;
    value = parseInt(value, 10);
    var totalValue = value+credits;
    document.getElementById("value").innerHTML = totalValue;
}

I already have a jquery function set up for when these images are clicked, but I want to be able to use the $credit_value variable from the PHP file. This is the start of my jquery function:

$().ready(function () {
    $('img.clickableImage').click(function () {
        if ($(this).data('selected')) { ......

3 Answers 3

1

In your echo statement, put a custom data-* attribute like

echo "<img data-credit='". $credit_value ."' src= '$link[Image_Link] . /133x100' id='$row[Item_Name]' title='$row[Item_Name]' class='clickableImage' alt='$just_name' border=0 style='position: relative; top: 0; left: 0;'/>";

and then in your click handler access it like

$('img.clickableImage').click(function () {
        var credit = $(this).attr('data-credit');
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can use data-*prefixed custom attribute, Set the value

echo "<img  data-creditvalue='. $credit_value .' ......../>";

Script, to fetch use $.fn.data() as you are already using $(this).data('selected')

var creditvalue = $(this).data("creditvalue")

2 Comments

are you my evil twin :) ?
@AmmarCSE, You can call be twin but not evil :) Our though process is quite same
0

Use Event delegation

 $(document).ready(function () {
    $(document).on('click', 'img.clickableImage', function () {
            if ($(this).data('selected')) {
               // here your code
            }
    });
 });

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.