简体   繁体   中英

Hide a form based on the selected option in drop down menu

I am having some trouble with the following scenario:

What I need is a way to hide a form if a option is selected in a drop down menu. The goal is to have the user select how they want to pay, either by credit card or thru PayPal. If they select Credit Card, then the Credit Card form is displayed (which is the default method of payment). If they select PayPal, then the PayPal form will show and the Credit Card from will be hidden. Here is my HTML so far: (it would be nice if this could be done with jQuery)

<select id="payment_type" name="payment_type">
   <option value="Credit">Credit/Debit Card</option>
   <option value="PayPal">PayPal Account</option>
</select>


<div id="credit_card_payment">
<h2>Enter Credit/Debit Card Details:</h2>
....


<form id="paypal_payment" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="clearfix">
....

You need something like this (jQuery):

$('#payment_type').change(function(){
    if($(this).val() == "PayPal") {
        $('#credit_card_payment').hide();
        $('#paypal_payment').show();
    } else {
        $('#credit_card_payment').show();
        $('#paypal_payment').hide();
    }
});   
$("#payment_type").change(function (){
//add an if else on $(this).val(), use $("#...").hide() or show()
})

Here's a working example: http://jsfiddle.net/CYzsY/

You want your forms hidden before a value is selected. The way to do this would be to set the CSS on your forms to display: none by default. This will hide the forms and take up no screen space. In the example above, we do this with: .hidden { display: none } .

To show a form when a particular value is selected, you simply need to show/hide depending on the input selection.

I would also suggest a stylistic change to your HTML/CSS. Instead of underscores, you should consider using dashes. So id="payment_type" would be id="payment-type" . This has the benefit of being easier to type, and shares similar syntax with CSS properties such as border-width .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM