开发者

How to modify my jQuery script to add a math function and pass the result?

You can find my jQuery in this fiddle http://jsfiddle.net/qSkZW/9/ where the value changes based on your dropdown selection.

What I need is to multiply the selected quantity with a PHP variable. For example when$price = '10'; and you select 3 for quantity, you get an output of 30.

Also, how can I pass the result to display it in the next page ?

Thank you.

What I am trying to clone is the Your Purchase system found here https://www.groupon.com/deals/pizza-delight/confirmation?ms=false&pledge_id=538463 开发者_StackOverflow中文版that you add the quantity and you get the final price.


 $("#quantity").change(function () {
     var str = $(this).val();
     $("#here").text(parseInt(str, 10) * <?php echo $price; ?>);
 }).change();

Your updated fiddle.


The simplest method is to store the php value in a js variable - which you can reference in your js function. Eg...

<script>
var price = <?php echo $price ?>;
</script>

In addition you can encode php vars as json for easy js access. Eg...

<?php

$products = array(
    'Hot socks' => array(
        'price' => 10,
        'description' => 'These socks are steaming HOT!',
    ),
    'Cool socks' => array(
        'price' => 20,
        'description' => 'The perfect treat for for feet on those hot summer days!',
    ),
);

?>

<script>

var products = <?=json_encode($products)?>;

alert('Please buy some hot socks @ ' + products['Hot socks'].price);

</script>

edit: example is scarf compatible


Just output the integer directly into the script using php:

$("#quantity").change(function () {
    var price = parseInt($(this).val(), 10)*<?php echo $price; ?>
    $("#here").text(price);
}).change();

Using PHP 5.4 or short tags enabled:

var price = parseInt($(this).val(), 10)*<?=$price?>


You can just echo onto the page in your javascript:

<script>
    // some js above here
    php_val=<?php echo $price; ?>
    // some js that uses php_val down here
</script>


You can use HTML5 custom attributes:

<select data-price="10"> ... </select>

And then get it with jQuery:

 $("#quantity").change(function () {
   var el = $(this);
   var str = el.val() * el.attr('data-price');
    $("#here").text(str);
 })
 .change();

Storing it in a var price value is not a good solution as it doesn't specify a select element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜