LeoMogMooseBell LeoMogMooseBell - 2 months ago 7
Javascript Question

box checks even though an alert is thrown?

I would like to have it set up. So when it has gone above a certain value an alert is raised to inform the user has ticked too many boxes. The alert appears successfully but the checkbox in question keeps ticked. I have used this function before but it is not working this time. I don't know why. Thanks in advance for any help is given.

function cannotDoThreeATTandAwareness() {
var i = 0;
$('.ATT, #aware').each(function() {
if ($(this).is(':not(:visible)')) {
i += 3
}
});
$('.ATT').each(function() {
if ($(this).is(':checked')) {
i += 3
}
});
$('.awareness').each(function() {
if ($(this).is(':checked')) {
i += 1
}
});

if (i > 9) {
alert('You cannot select this paper as you have already selected your Core 2 paper');
};

return i == 10;
}


onclick =" if(cannotDoThreeATTandAwareness()){this.checked=false};"



Answer

Simply return the result you want inside the click event too.

function cannotDoThreeATTandAwareness() {
  var i = 0;
  // used 'true' to always make it fail, for the sake of example
  if (true || i > 9) { 
    alert('You cannot select this paper as you have already selected your Core 2 paper');
  };

  return i > 9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox" onclick="return cannotDoThreeATTandAwareness()">
  Click me
</label>

Another option would be to add an argument to the function, let's say e, and where you want to block the change, you can use e.preventDefault(). In order for this to work, you'll need to pass the event down to the function, here's a snippet:

function cannotDoThreeATTandAwareness(e) {
  ...
  if (true || i > 9) {
    e.preventDefault()
    ...
  };
}

<input type="checkbox" onclick="cannotDoThreeATTandAwareness(event)">
Comments