1

I am currently trying to pass data from my server to my main page. I currently have my php echoing for each returned result:

while($row = mysql_fetch_array($result))
{
    echo "<img class='s' id=" . $row['id'] . " src=QR/" . $row['src'] ".png>";

}

when i tried adding a field, num, after id:

<img class='s' id=(rowid) num=".$row['num']." .......

I get undefined when i use

alert(this.num)

but

alert(this.id)

works. How can I pass the num value too?

EDIT:

Hey Everyone, thanks for you help, I have included a jsfiddle on how i solved this problem. http://jsfiddle.net/3yzcx/4/

I had to use jQuery and used .attr() to define my own attribute called num and called that out.

4
  • 2
    possible duplicate of Custom attributes - Yay or nay?
    – jcolebrand
    Jul 9, 2011 at 4:19
  • Thanks, ya, in simpler terms I guess I was making a custom attribute
    – d.mc2
    Jul 9, 2011 at 4:25
  • Would I be able to use $(img).attr(num)?
    – d.mc2
    Jul 9, 2011 at 4:29
  • 1
    using jQuery? Yes, absolutely.
    – jcolebrand
    Jul 9, 2011 at 4:50

4 Answers 4

4

Very simple. id is a valid property for the img tag. num is not. You can't assign arbitrary properties to a tag and expect it to work.

If you want to pass your PHP data to javascript, using a hidden form element or even more simply something like this:

<?php
echo '<script type="text/javascript">';
echo 'var num = ' . $num . ';';
echo '</script>';
?>

Of course I know you're in a loop, this is just an example. You could easily make it an array or something.

2

Adding properties doesn't work. You'll want to add an <input type=hidden value='num'> or something inside the <div> where num is your number data. You'll need to make the input field addressable by giving it an ID as well:

echo("<input type=hidden id=\"$row[id]-num\" value='num'>");

Also, I see a closing div tag but no opening tag. You'll want to fix that!

1

Technically you are not supposed to assign custom attributes. Jcolebrand's original post is worth an upvote due to the discussion about the data prefix. However, even though it is technically not correct, you should be able to get the value with the getAttribute() function.

this.getAttribute("num");

That will work in Firefox, but no guarantees in other browsers.

-1

I've not tried this outside of jQuery, but within that framework you would use

alert(this.attr("num"));

to retrieve non-standard attributes. May work with plain javascript as well, but I've not tried it.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.