默认情况下,Button通过javascript

时间:2020-04-10 02:41:25

标签: javascript php

我有以下带有选项的选择器:

<select name="" id="product-selector" class="list_item">
    <?php

    if( have_rows('section_a') ):
    while( have_rows('section_a') ): the_row();
    if( have_rows('product_item') ):
    while( have_rows('product_item') ): the_row();

    $product_item_quantity = get_sub_field('product_item_quantity');
    $product_item_price = get_sub_field('product_item_price');
    $product_item_id = get_sub_field('product_item_id');
    $product_item_variation_id = get_sub_field('product_item_variation_id');
        ?>
        <option value="<?php echo $product_item_variation_id; ?>" data-id="<?php echo $product_item_variation_id; ?>" data-content="<?php echo $product_item_quantity; ?> <span class='price' data-count='<?php echo $product_item_quantity; ?>' data-price='<?php echo $product_item_price; ?>'><?php echo $product_item_price; ?>"> </option>
    <?php endwhile; endif; endwhile; endif; ?>
</select>

我有以下按钮:

<div class="submit">
<a class="btn btn-warning" id="purchase" href="?add-to-cart=<?php echo $product_item_id; ?>&variation_id=<?php echo $product_item_variation_id; ?>">Order Now</a>
</div>

我的JavaScript是:

<script>
document.getElementById("product-selector").onchange = function() {
    document.getElementById("purchase").href = "?add-to-cart="+"<?php echo $product_item_id; ?>"+"&"+"variation_id="+this.value+"/";
}
</script>

当用户单击“订购”按钮时,链接会动态更改-它获得{的值,并且应该通过<?php echo $product_item_variation_id; ?>"获得"variation_id="+this.value+",并且运行正常,但是在页面加载时,{{ 1}}的按钮值获得LAST选项值,但不是第一个(默认)值。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为您应该创建一个变量以保存第一个值。因为您已经循环。因此默认值为选择的最后一个值。

<?php $product_item_variation_id_first = ""; ?>
<select name="" id="product-selector" class="list_item">
    <?php

    if( have_rows('section_a') ):
    while( have_rows('section_a') ): the_row();
    if( have_rows('product_item') ):
    while( have_rows('product_item') ): the_row();

    $product_item_quantity = get_sub_field('product_item_quantity');
    $product_item_price = get_sub_field('product_item_price');
    $product_item_id = get_sub_field('product_item_id');
    $product_item_variation_id = get_sub_field('product_item_variation_id');
    if ($product_item_variation_id_first == "")
        $product_item_variation_id_first = $product_item_variation_id;
        ?>
        <option value="<?php echo $product_item_variation_id; ?>" data-id="<?php echo $product_item_variation_id; ?>" data-content="<?php echo $product_item_quantity; ?> <span class='price' data-count='<?php echo $product_item_quantity; ?>' data-price='<?php echo $product_item_price; ?>'><?php echo $product_item_price; ?>"> </option>
    <?php endwhile; endif; endwhile; endif; ?>
</select>

<div class="submit">
<a class="btn btn-warning" id="purchase" href="?add-to-cart=<?php echo $product_item_id; ?>&variation_id=<?php echo $product_item_variation_id_first; ?>">Order Now</a>
</div>
相关问题