PHP if Checkbox checked show list

时间:2015-07-28 23:32:23

标签: php

I want to display a list based on some php parameters.

Instead of having both options appear by default (because they have the deposits parameter enabled on the post), i want to have the pay in full option enabled by default, and the payment plan option only to appear after a checkbox is checked.

I have tried a million different approaches but I have a pretty limited experience in php.

Heres the code:

<div class="wc-deposits-wrapper <?php echo WC_Deposits_Product_Manager::deposits_forced( $post->ID ) ? 'wc-deposits-forced' : 'wc-deposits-optional'; ?>">
<?php if ( ! WC_Deposits_Product_Manager::deposits_forced( $post->ID ) ) : ?>
    <ul class="wc-deposits-option">
        <li><input type="radio" name="wc_deposit_option" value="yes" id="wc-option-pay-deposit" /><label for="wc-option-pay-deposit">Pay Deposit</label></li>
        <li><input type="radio" name="wc_deposit_option" value="no" id="wc-option-pay-full" /><label for="wc-option-pay-full">Pay in Full</label></li>
    </ul>
<?php endif; ?>

And here is my awful attempt at what I want, perhaps you can decipher it!

<div class="wc-deposits-wrapper <?php echo WC_Deposits_Product_Manager::deposits_forced( $post->ID ) ? 'wc-deposits-forced' : 'wc-deposits-optional'; ?>">
<?php if ( ! WC_Deposits_Product_Manager::deposits_forced( $post->ID ) ) : ?>

    <ul class="wc-deposits-option">
    <li><input type="radio" name="wc_deposit_option" value="no" id="wc-option-pay-full" /><label for="wc-option-pay-full">Pay in Full</label></li>
    </ul>

    <?php endif; ?>

<input type="checkbox" name="plans" value="yes">    

<?php if ( isset($_POST['plans']) ) : ?>

    <ul class="wc-deposits-option">
        <li><input type="radio" name="wc_deposit_option" value="yes" id="wc-option-pay-deposit" /><label for="wc-option-pay-deposit">Pay Deposit</label></li>
    </ul>
<?php endif; ?>

Thanks in advance for any help in this!

1 个答案:

答案 0 :(得分:0)

我建议使用jQuery代替纯PHP解决方案。如果您对PHP解决方案有要求,则可以,但正如其他评论中所述,它需要重新加载页面。

这是你在jQuery中如何处理它的方法:

如果您为复选框添加了ID,例如:<input type="checkbox" id="plans-checkbox" name="plans" value="yes">

并且,当您选中计划框时,您只需要显示您想要显示的字段的ID(仅限一个,因为ID只能发出一次),如下所示:

<ul class="wc-deposits-option" id="pay-deposit-ul">

然后你可以使用这样的jQuery来切换选项,而无需重新加载页面。

// Hide the pay deposit ul by default (you could also handle this with CSS by giving display:none; to the ID)
$("#pay-deposit-ul").hide();

$("#plans-checkbox").change(function() {
    if ($(this).checked) {
        // Plans checkbox is selected
        $("#pay-deposit-ul").show(); // #pay-deposit-ul means jQuery selects the ID of the name pay-deposit-ul
    }
    else
    {
        // Plans checkbox is unselected
        $("#pay-deposit-ul").hide();
    }
 });

我希望有所帮助。如果你以前从未使用过jQuery,那就不用担心了。有大量的在线资源可以涵盖基础知识(如http://andreehansson.se/the-basics-of-jquery/),您会发现,与用户界面进行交互时,它非常方便,节省了大量时间。