Jerry Chequer Jerry Chequer - 20 days ago 10
Javascript Question

Javascript/jQuery If Condition

I am currently having an issue getting my jQuery if statement to work. I have been looking at online tutorials on if statements in Javascript as well as the documentation on jQuery to try and get this to work however still can not manage to. I have included a snippet of my JS below.

($('#modem-include').click(function () {
if ($(this).hasClass("btn-info")) {
$(this).addClass("btn-success");
$(this).removeClass("btn-info");
$(this).text("SELECTED");
} else {
$(this).text("SELECTED");
}
if ($('#modem-nothanks').hasClass("btn-success")) {
$(this).addClass("btn-info");
$(this).removeClass("btn-success");
$(this).text("SELECT");
} else {
$(this).text("SELECT");
}
}));
($('#modem-nothanks').click(function () {
if ($(this).hasClass("btn-info")) {
$(this).addClass("btn-success");
$(this).removeClass("btn-info");
$(this).text("SELECTED");
} else {
$(this).text("SELECTED");
}
if ($('#modem-include').hasClass("btn-success")) {
$(this).addClass("btn-info");
$(this).removeClass("btn-success");
$(this).text("SELECT");
} else {
$(this).text("SELECT");
}
}));


No matter what I try this does not seem to work.

Wondering if I am missing something obvious?

Thanks in advance.

Answer

If I understood it right (which I'm not sure), try something like:

$('#modem-include').click(function () {
  var $this = $(this), $that = $('#modem-nothanks');
  if ($this.hasClass("btn-info")) {
      $this.removeClass("btn-info");
      $this.addClass("btn-success");
      $this.text("SELECTED");
  } else {
      $this.text("SELECT");
  }
  if ($that.hasClass("btn-success")) {
      $that.removeClass("btn-success");
      $that.addClass("btn-info");
      $that.text("SELECT");
  } else {
      $that.text("SELECTED");
  }
});
$('#modem-nothanks').click(function () {
  var $this = $(this), $that = $('#modem-include');
  if ($this.hasClass("btn-info")) {
      $this.removeClass("btn-info");
      $this.addClass("btn-success");
      $this.text("SELECTED");
  } else {
      $this.text("SELECT");
  }
  if ($that.hasClass("btn-success")) {
      $that.removeClass("btn-success");
      $that.addClass("btn-info");
      $that.text("SELECT");
  } else {
      $that.text("SELECTED");
  }
});
Comments