shgan
shgan

Reputation: 133

JavaScript Check box with collapse button

I want to make below code works for Check box with collapse button.

<label>
    <input type="checkbox" id="postageyes" name="postage1" value="Yes" />Yes</label>
<div id="conditional1">
    <p>This should only show when the 'Yes' checkbox &lt;input&gt; element is checked.</p>
    <a href="">close</a>
</div>

Javascript

var conditionalContent1 = $('#conditional1'),
group = $('input[type=checkbox][name=postage1]');

group.change(function() {
   conditionalContent1.toggle(group.filter(':checked').val() === 'Yes');
}).change();

when i checked check box new div open, I want to get done is. when i click close link, the open div close and unchecked the checked box.How to do this. anyone can help?

Upvotes: 1

Views: 2027

Answers (3)

Dave Knight
Dave Knight

Reputation: 1

EDIT: Tushar updated his answer while I was writing this so... yeah, never mind! That would also work. The point still stands, though.


I think part of the problem is that you're trying to use an anchor tag inappropriately. Leaving the href blank will reload the page, so Tushar's answer looks right but doesn't actually do what you're asking. Use a button (and style it appropriately if you still want it to look like a link) and then handle its click event to toggle the checkbox and hide the content.

I've modified Tushar's jsfiddle to show what I mean. You'll probably be able to make it more streamlined than this, but the simple version is:

Replace the a tag with:

<button id="closeButton">close</button>

Then add the following to the js:

$('#closeButton').on('click', function () {
    $('#postageyes').click();
});

https://jsfiddle.net/pnq8zu0L/

Upvotes: 0

Tharindu Kumara
Tharindu Kumara

Reputation: 4458

You can use the toggle function and click event to achieve what you have mentioned.

$('#postageyes').click(function() {
  $('#conditional1').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label>
  <input type="checkbox" id="postageyes" name="postage1" value="Yes" />Yes</label>
<div id="conditional1" style="display:none">
  <p>This should only show when the 'Yes' checkbox &lt;input&gt; element is checked.</p>
  <a href="">close</a>
</div>

Upvotes: 1

Tushar
Tushar

Reputation: 87203

You can use change event on checkbox. And toggle to hide/show div.

$('#postageyes').on('change', function() {
    $('#conditional1').toggle($(this).is(':checked'));
});

$('#conditional1').on('click', 'a', function() {
    $('#postageyes').prop('checked', false);
    $('#conditional1').hide();
    return false;
});

Demo: http://jsfiddle.net/tusharj/n7044syx/1/

Upvotes: 1

Related Questions