views:

758

answers:

3

I have the following which i use in a traditional onclick event for a DIV tag

How would I go about implementing this using jquery?

$parameter = "onClick=\"selprice('" .
  $price_options_array[$price_counter]['price'] . "','" .
  $price_counter . "')" . "\"";

I use the above and just add it to my div like so:

<div class="price_row" <?php echo $parameter; ?>>

I have this so far using the jquery method but Im not sure how to proceed?

$(document).ready(function() {
  $('.price_row').click(function() {
    ????
  });
});
+5  A: 
$(function() {
  $("div.price_row").click(function() {
    selprice("<?php echo $price_options_array[$price_counter]['price'] ?>", "<?php echo $price_counter ?>");
  });
});

I wouldn't necessarily advise it however. Another approach is to put the necessary date in a place you can query it at runtime. For example:

<div class="price_info")
  <div class="price"><?php echo $price_options_array[$price_counter]['price'] ?></div>
  <div class="counter"><?php echo $price_counter ?></div>
</div>

combined with CSS:

div.price_info div.price, div.price_info div.counter { display: none; }

and then:

$(function() {
  $("div.price_row").click(function() {
    var price = $(this).children("price").text();
    var counter = $(this).children("counter").text();
    selprice(price, counter);
  });
});

Dynamically generated Javascript can sometimes get a bit messy.

You can also use jquery.data() instead of using child elements. You just need to construct the class attribute correctly in PHP to include the necessary data.

cletus
FYI, typo in there '<div class="price_info")'
seth
+1: I was writing the same solution as you but you came up with it first! Very good :)
kuroir
It appears his price_counter is inside a non-listed PHP loop so your first example looks like it wouldn't work.
Crad
thanks for the time to write this all out for me, i will study it and see how i can best use this :-)
chicane
A: 

Move your $price_options_array to a javascript array.

'var price_options = ' . $price_options // or however you do it in PHP

And when you make your div inside your loop add an extra tag with the price_counter (pc)

">"

The "pc" variable will then be accessible in the jquery loop, as will the price_options info

$(document).ready(function() {

$('.price_row').click(function() { var pc = $(this).attr('pc'); var price = price_options[pc]['price']; selprice(price, pc); }); });

Hope that helps.

Dave
thanks i will try this out too...
chicane
A: 

You could do something like:

PHP:

<script language="text/javascript">var price_options = <?php echo json_encode($price_options_array); ?></script

for ( $y = 0; $y < $prices; $y++ )
{
  echo '<div class="price_row" id="price_' . $y . '">Foo</div>';
}

And in jQuery:

$('div.price_row').click(function(){
    var id = $(this).attr('id').split('_');
    selprice(price_options[id], id);
});

This is untested but it should give you a rough start.

Crad