Search code examples
javascripthtmljqueryformsradio-button

Append error message only when radio button is not checked on button click


I am trying to show an error if a user presses submit and doesn't check one of the radio buttons. That part works fine. Now, my issue is that even when the radio button is checked and the user presses the button.. the error shows right before the form submits. Why is that error showing when the radio button is checked? Any help will be appreciated.

HTML:

<form action="javascript:void(0);">
  <input type="submit" class="add-cart " value="Add">
  <br />

  <p class="option-name">Size : </p>
  <input type="radio" required="required" aria-required="true" id="product1" value="1" name="options[]" />
  <label class="label" for="product1">Small</label>

  <input type="radio" required="required" aria-required="true" id="product3" value="3" name="options[]" />
  <label class="label" for="product3">Medium</label>

  <input type="radio" required="required" aria-required="true" id="product4" value="4" name="options[]" />
  <label class="label" for="product4">Large</label>

  <input type="radio" required="required" aria-required="true" id="product5" value="5" name="options[]" />
  <label class="label" for="product5">X-Large</label>
</form>

JS:

$(document).ready(function() {
  var count = 0;
  $(".add-cart").click(function() {
    if (!$("input[name='options']").is(':checked') && count <= 0) {
      $(".option-name").append("<p class='option-error'>This field is required</p>");
      count++;
    }
  });
});

JSFiddle Demo


Solution

  • You're not currently resetting between uses, here's a new version:

    $(document).ready(function() {
      $(".add-cart").click(function() {
        $(".option-error").html("");
        if (!$("input[name='options[]']:checked").val()) {
          $(".option-error").html("This field is required");
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form action="javascript:void(0);">
      <input type="submit" class="add-cart " value="Add">
      <br />
    
      <p class="option-name">Size : <p class="option-error"></p></p>
      <input type="radio" required="required" aria-required="true" id="product1" value="1" name="options[]" />
      <label class="label" for="product1">Small</label>
    
      <input type="radio" required="required" aria-required="true" id="product3" value="3" name="options[]" />
      <label class="label" for="product3">Medium</label>
    
      <input type="radio" required="required" aria-required="true" id="product4" value="4" name="options[]" />
      <label class="label" for="product4">Large</label>
    
      <input type="radio" required="required" aria-required="true" id="product5" value="5" name="options[]" />
      <label class="label" for="product5">X-Large</label>
    </form>