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?

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Very thoughtful. Just the thing I was looking for. Thanks.
2

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

Comments

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>

3 Comments

This is how I often do it - just a handy note, \D is the same as [^0-9] :)
Regular expressions that are intuitive? Good luck :P +1 for doing it similar to my suggestion too :)
Well to some extent possible I guess :)

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.