0

Codes here

<form onclick="sa();">
<div id="rates">
<input type="radio" id="r1" name="rate" value="0"> X1
<input type="radio" id="r2" name="rate" value="1"> X2
<input type="radio" id="r3" name="rate" value="2"> X3
</div>
</form>

When I click any radio button X1 X2 or X3, sa() is supposed to be called, which changes the limit from 3 to 2. (The alert window is for testing use.) Then the limit is used to restrict the number of checkboxes selected in the lower part. But the function doesn't work when I click the buttons; no alert window pops up, and I can still choose 3 boxes.

Another question I would like to ask: if a user has checked some boxes, but then s/he returns to the X buttons and select another one, I would like to have all boxes unchecked and s/he needs to check them again. What's code for this? Just add the uncheck function to the onclick?

1 Answers1

0

The function is being defined inside a load handler and thus is in a different scope

Inline event handler not working in JSFiddle

limit = 3;

function sa() { //var rates = document.getElementsByName('rate');
  limit = 2;
  window.alert(limit);
  //if (rates[1].checked) {limit=1;}
  //else if (rates[2].checked) {limit=2;}
  //else if (rates[3].checked) {limit=3;}
  //else {limit=2;}
}
$('form').on('click', function(evt) {
  sa();
});


$('input.single-checkbox').on('change', function(evt) {
  if ($(this).siblings(':checked').length >= limit) {
    this.checked = false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
  <p><strong>No:</strong></p>
  <input type="radio" name="no" value="0" checked> Unrestricted
  <input type="radio" name="no" value=1> 1
  <input type="radio" name="no" value=2> 2
  <input type="radio" name="no" value=3> 3
  <input type="radio" name="no" value=4> 4 or more
</form>

<form>
  <div id="rates">
    <input type="radio" id="r1" name="rate" value="0"> X1
    <input type="radio" id="r2" name="rate" value="1"> X2
    <input type="radio" id="r3" name="rate" value="2"> X3
  </div>
</form>

<div class="pricing-levels-3">
  <p><strong>Must include:</strong></p>
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike"> A
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike"> B
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike"> C
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike"> D
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike"> E
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike"> F
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike"> G
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike"> H
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike"> I
  <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike"> J
</div>
Maksym Semenykhin
  • 1,924
  • 15
  • 26