g2902249 g2902249 - 2 months ago 18
PHP Question

passing varibles into j-query from php as attributes

i am trying to pass the attribute

location
into jquery but unable to do so
could some one point out on what m i doing wrong

php

<?php echo "<a class='classloader' location='$array[$i]' href='#'>$array[$i]</a>"; ?>


Jquery

<script type ="text/javascript">
$(document).ready(function () {
var location= $(this).attr('location');
$(".classloader").click(
function () {
display();
}
);
});

function display() {
$('#contenthere').html(location);
}

</script>

Answer

You're using $(this) outside the click handler, so it doesn't refer to the element that they clicked on.

Then you should pass the string as an argument to display().

$(".classloader").click(function() {
    var location = $(this).attr("location");
    display(location);
});

function display(str) {
    $('#contenthere').html(str);
}

BTW, you shouldn't make up your own attributes like that, they might conflict with future HTML versions. Use data-XXX attributes, which are reserved for programmers.

<?php echo "<a class='classloader' data-location='$array[$i]' href='#'>$array[$i]</a>";  ?>

Then in jQuery you can use $(this).data('location') to access it.

Comments