-3

I want that whenever I add on button then a class should append and after next click class should remove. I tried with following code but class not removing in second click here is my code.

$("#hide_show_keypad").click(function (e) {
  $(this).addClass("fcurrent").siblings().removeClass("fcurrent");
});
<input type="submit" name="btn" id="hide_show_keypad" class="mytest" >
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • probably `siblings` is the wrong function here? – Alex Aug 20 '18 at 08:28
  • on your click you can add an `if` condition and check if the class exist on the element or not as `if($(this).hasClass('fcurrent')) $(this).removeClass('fcurrent'); else $(this).addClass('fcurrent');` – vikscool Aug 20 '18 at 08:29
  • in pure JS: `element.classList.toggle('yourclass');` – AymDev Aug 20 '18 at 08:29

2 Answers2

0

Use toggleClass() to make it work as you want.

$("#hide_show_keypad").click(function(e) {
  $(this).toggleClass("fcurrent")
});

Demo

$("#hide_show_keypad").click(function(e) {
  $(this).toggleClass("fcurrent")
});
.fcurrent{color:blue;background-color:yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" name="btn" id="hide_show_keypad" class="mytest" />
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
0

$('#btn').click(function() {
  $('#paragraph').toggleClass("style");
});
.style {
  background-color: #000;
  color: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="paragraph">This is a sample paragraph.</p>
<br/>
<button type="button" id="btn">Click Me</button>
Anshuman
  • 758
  • 7
  • 23