【问题标题】:Need to make a field required when radio button is 'Yes' and not required when 'No'单选按钮为“是”时需要填写字段,“否”时不需要填写
【发布时间】:2017-12-08 05:13:52
【问题描述】:

我已在此网站上搜索并尝试了所有建议,但在单选按钮上选择“否”时无法获得不需要的文本字段。

目前,如果“是”和“否”未选中,则文本字段不是必需的,因此将提交表单。 但是,如果任何一个字段都被选中,那么即使是“否”也需要它:-(

我这里有演示:https://jsfiddle.net/ba9ahpyx/

我只希望在“field_1”单选按钮上选择“是”时需要输入“field_2”。

I will be hiding the text field when 'No' is selected but have removed that code for now to keep it simple.

HTML

<form method="post" action="#">
<div>
  <div class="radio">
    <span class="label">Do you have your own website? (required)</span>
      <div>
        <label><input type="radio" name="field_1" value="Yes"> Yes</label>
        <label><input type="radio" name="field_1" value="No"> No</label>
      </div>
  </div>
</div>

<div>
  <label for="field_2">Website URL </label>
  <input type="text" name="field_2" id="field_2" value="" />
</div>

<div>
  <input type="submit" value="Submit">
</div>  
</form>

jQuery

$(document).ready(function(){
    $('input[name="field_1"]').change(function () {
        if(this.checked) {
            $('#field_2').prop('required',true);
        } else {
            $('#field_2').prop('required',false);
        }
    });
});

感谢您的帮助。

【问题讨论】:

  • 您只是在测试该字段是否为checked,但您说您还想测试该值是否为“是”。建议您尝试将其作为过滤器添加到您的事件挂钩或修改为 if 语句。

标签: jquery html


【解决方案1】:

使用以下更改 jquery,它将为您工作

$(document).ready(function(){
    $('input[name="field_1"]').change(function () {
        if($(this).val() =='Yes') {
            $('#field_2').prop('required',true);
        } else {
            $('#field_2').prop('required',false);
        }
    });
});

【讨论】:

  • 感谢 Prateik,完美运行。我应该在几天前问这个问题并减轻我的压力,再次欢呼:)
猜你喜欢
  • 2016-01-19
  • 2011-12-25
  • 2013-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
相关资源
最近更新 更多