Garrettj944 Garrettj944 - 6 months ago 36
Javascript Question

jQuery - Can't add a class to a button with an onClick event

I am trying to add a class to a button that has an

onClick
event. The
onClick
event triggers a popup
alert
that tells the user to check a box. Once you check a box, it disables the
onClick
:
$("#continue").prop('onclick',null).off('click');
Once the
onClick
is disabled, I want to add a
class
to the button once it is clicked:

//Updated JS
jQuery(function($) {
if ($("#continue").hasClass("selected")) {
$(this).addClass('active');
}
$('#button').click(function(){
$("#continue").addClass('selected');
$("#continue").prop('onclick',null).off('click');
});
});

//Button HTML
<a id="button" href="javascript:void(0)">Pick me</a>
<a id="continue" href="javascript:void(0)" onclick="showError()">Continue</a>


But no
class
gets added. Not sure whats going on.

Answer

Maybe you can trigger a function to validate if the element has the required class like this:

function validate(element) {
  if ($(element).hasClass('selected')) {
    $(element).addClass('active');
  } elseĀ  {
    alert("this is an error");
  }
}

$(function() {
  $('#button').click(function() {
    $("#continue").addClass('selected');
  });

});
.selected {
  color: red;
}
.active {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a id="button" href="javascript:;">Pick me</a>
<a id="continue" href="javascript:;" onclick="validate(this)">Continue</a>

Comments