Robinhood
Robinhood

Reputation: 899

How to toggle a button?

I have created a small code where there is a "Add a debit or credit card" button. I have hidden all the content inside that button by default.

Upon click of the button, I want to show the content and again upon click on the button, I want to hide the content.

In my code when I click on the button it disappears and there is no option to toggle again.

$('#addNewCard').hide();
$('#addCard').click(function () {
   $('#addNewCard').show();
   $('#addCard').toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn-cal" id="addCard">Add a debit or credit card</button>

<div id="addNewCard">
  <p>Card details here</p>
</div>

Upvotes: 0

Views: 121

Answers (3)

Matt Saunders
Matt Saunders

Reputation: 4074

$('#addCard').toggle();

Will be toggling the visibility of #addCard, which is your button.

It should just be:

$('#addCard').click(function () {
    $('#addNewCard').toggle();
});

Upvotes: 2

Akinjiola Toni
Akinjiola Toni

Reputation: 678

Using jQuery, i suggest you hide the #addNewCard element using css display none and then toggle visibility correctly with javascript.

$('#addCard').click(function () {
   $('#addNewCard').toggle();
});

$('#addCard').click(function () {
   $('#addNewCard').toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button type="button" id="addCard">Add a debit or credit card</button>
<div id="addNewCard" style="display:none;">
  <p>Card details here</p>
</div>

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Instead of hiding the button, change the button text, also use .toggle() for $('#addNewCard'):

$('#addNewCard').hide();
$('#addCard').click(function() {
  $('#addNewCard').toggle();
  $('#addCard').text($('#addCard').text() === "Hide Debit Card" ? "Add a debit or credit card" : "Hide Debit Card");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn-cal" id="addCard">Add a debit or credit card</button>

<div id="addNewCard">
  <p>Card details here</p>
</div>

Upvotes: 4

Related Questions