【问题标题】:Append error message only when radio button is not checked on button click仅在单击按钮时未选中单选按钮时才附加错误消息
【发布时间】:2017-10-04 22:00:10
【问题描述】:

如果用户按下提交但未选中其中一个单选按钮,我会尝试显示错误。那部分工作正常。现在,我的问题是,即使选中了单选按钮并且用户按下了按钮..错误在表单提交之前显示。为什么选中单选按钮时会显示该错误?任何帮助将不胜感激。

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

【问题讨论】:

  • 你没有减少计数...
  • @Jonasw 我这样做只是为了不附加相同的错误消息 20 次
  • 在这种情况下,最好使用 boolean 然后...

标签: javascript jquery html input radio


【解决方案1】:

您目前没有在两次使用之间进行重置,这是一个新版本:

$(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>

【讨论】:

  • 第一次点击有一个小错误...错误仍然出现
  • @user4756836 更新了它。请记住标记为解决方案:它很有帮助。
猜你喜欢
  • 1970-01-01
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多