Raj
Raj

Reputation: 555

How to display <div> content based on Radio button using Jquery

I Want to display <div class="Add1"> content based on <div class="delivery"> selection. Please help me. Thank you in advance.

My code:

<div class="delivery">
    <label>
        <input type="radio" name="DeliveryChoice" value="false" checked />
        <span>Deliver my order to me</span>
    </label>
    <label>
        <input type="radio" name="DeliveryChoice" value="true"  />
        <span>I will pick up my order</span>
    </label>
    <label>
        <input type="radio" name="DeliveryChoice" value="true" />
        <span>I will pick</span>
    </label>
</div>

<div class="Add1">
 <div>Order address</div>

  <div>Order </div>

   <div>Order me</div>

</div>

The JQuery is:

var address = $('.Add1');
$('.delivery input[type="radio"]').change(function() {
    console.log($(this).val());
     if ($(this).val() === 'false') {
        address.hide();
    }
   else if ($(this).val() === 'true') {
        address.show();
    } else {
        address.show();
    }
});

Upvotes: 0

Views: 810

Answers (1)

user3559349
user3559349

Reputation:

Start by giving each of the <div> elements in id attribute

<div class="Add1">
    <div id="A">Order address</div>
    <div id="B">Order</div>
    <div id="C">Order me</div>
</div>

and add a data attribute to your radio buttons matching the appropriate id.

<div class="delivery">
    <label>
        <input type="radio" name="DeliveryChoice" value="false" data-divid="A" checked />
        <span>Deliver my order to me</span>
    </label>
    <label>
        <input type="radio" name="DeliveryChoice" value="true" data-divid="B" />
        <span>I will pick up my order</span>
    </label>
    <label>
        <input type="radio" name="DeliveryChoice" value="true" data-divid="C" />
        <span>I will pick</span>
    </label>
</div>

Then the script becomes

var divs = $('.Add1').children('div');
$('.delivery input[type="radio"]').change(function() {
    var id = $(this).data('divid');
    divs.hide(); // hide all
    $('#' + id).show();
});

and style your 2nd and 3rd divs as hidden initially

.Add1 div:not(:first-of-type) {
  display:none;
}

Refer updated fiddle

Upvotes: 1

Related Questions