1

I just read in a best practices article for jquery and ajax that I should avoid defining behavior for elements on the page with inline script. That does make sense since it makes the code very readable.

However, I want to ask what should I do then, if I need to pass server-side variables to javascript. Like consider the following code...

<?php foreach($product as $product_id): ?>
<input type="button" value="Delete Favorite" onclick="delete_favorite('<?php echo $product_id; ?>')" />
<?php endforeach; ?>

Should I be using hidden form values for such a case? or may be adding adding the server side variable in the id of element I am defining the behavior for? like so..

<input type="button" value="Delete Favorite" id="button<?php echo $product_id; ?>" />

Any suggestions?

vikmalhotra
  • 9,981
  • 20
  • 97
  • 137

3 Answers3

3

There are a few things you could do, one of them would be use a custom attribute such as data-product-id (data- prefix is in HTML5 spec I believe).

Though, you could also give that input an id such as product-343 and then get the id using...

$(this)[0].id.replace(/\D/g, '');

(assume this points to an input element).

alex
  • 479,566
  • 201
  • 878
  • 984
2

Use data- prefix attribute. http://jsfiddle.net/zJWfB/

aavezel
  • 604
  • 3
  • 10
1

Try this:

<?php foreach($product as $product_id): ?>
    <input id="fav-<?php echo $product_id; ?>" class="prod-fav" type="button" value="Delete Favorite"/>
<?php endforeach; ?>

<script type="text/javascript">
    $(function(){
        $(".prod-fav").click(function(){
                    var $this = $(this);
            var id = $(this).attr("id").replace(/[^0-9]/g, "");
            delete_favorite(id); // Call delete_favorite or
                    //delete_favorite.call($this, id); //To retain the calling element context or
                    // implement you delete function right here..
        });
    });

</script>
Chandu
  • 81,493
  • 19
  • 133
  • 134