【问题标题】:HTML Form Validation - Hiding required labels based on conditional validationHTML 表单验证 - 根据条件验证隐藏所需的标签
【发布时间】:2014-06-03 13:26:22
【问题描述】:

我有一个 HTML 表单,我正在使用 JQuery Validate 插件来要求某些表单字段是强制性的。我有一个带有 3 个选项的单选按钮字段:

小时 天 不确定

和另一个字段,用于输入与小时或天选择相对应的数字。如果用户选择“不确定”,则不需要输入数字。这很好用——当用户选择“不确定”时,“此字段是必需的”。标签消失了,但它仍然保留在数字输入字段中,即使不再需要它。一旦用户单击“不确定”单选按钮以使其不再需要呈现,我无法弄清楚如何使该标签消失。

这是我目前的 HTML:

<form role="form" action="#" method="post" id="durationForm">
 <tr>
 <td colspan = "3">Please enter the duration?</td>
 </tr>
 <tr>
<td width="10%"><input type="number" class="form-control" id="duration"  name="duration" required="true" /></td>
 <label for="durationNumber" class="validateError"></label>
 <td width="50%">
 <div class="controls">
 <label class="radio">
<input type="radio" name="radioduration" value="Hours" required="true" /> Hours</label>
 <label class="radio">
<input type="radio" name="radioduration" value="Days" required="true" /> Days</label>
 <label class="radio">
<input type="radio" name="radioduration" class="jradiodurationUnsure" value="Unsure" required="true" /> Unsure</label>
 <label for="radioduration" class="validateError"></label>
 </div>
 </td>
 </tr>

 <button type="submit" class="btn btn-primary">Next</button>
 </form>

这是脚本:

$(document).ready(function () {
     // initialize the plugin
     $("#durationForm").validate({ 
         errorClass: "validateError",
         rules: {
             duration: {
                 required: '.jradiodurationUnsure:unchecked'
             }
         }
         });
     }); 

我有一个jsfiddle 也展示了这一点。

【问题讨论】:

    标签: javascript jquery jquery-validate


    【解决方案1】:

    首先你必须像这样在最后一个不确定单选按钮上添加一个“id” -

    <input type="radio" name="radioduration" id="abc" class="jradiodurationUnsure" value="Unsure" required="true" /> 
    

    现在基于该 ID,您可以使用以下 JQuery 命令更新脚本部分 -

    $(document).ready(function () {
        $('#abc').click(function () {
            $('#duration').hide('fast');
        enter code here}); 
    });
    

    使用上面的命令,数字输入会隐藏。

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      相关资源
      最近更新 更多