首页 > 解决方案 > 当单选按钮选择为否时禁用需要消息

问题描述

当我选中单选按钮“否”时,我试图禁用所需的消息但是当我提交表单时没有任何反应,它只是重定向到同一页面并显示所需的消息

更新代码

//hide/show chapela  Yes/No
    $(document).ready(function () {
        $("input[name$='Chapel']").click(function () {
            var test = $(this).val();
            if (test == 'No') {
                $("div#hideChapel").hide();
            }
            else {
                $("div#hideChapel").show();
             }
        });
    });

    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', function () {
        history.pushState(null, null, document.URL);
    });



    $(document).ready(function () {
        var test = $(this).val();
        if(test == 'No'){       
            $("hideChapel").prop("required", false);
        }
        else {
            $("hideChapel").prop("required", true);
        } 
    });
<div class="form-group">
  @Html.LabelFor(model => model.Chapel, htmlAttributes: new { @class = "control-label col-md-3" })
  <div class="col-md-9">
    <label class="radio-inline">
      @Html.RadioButtonFor(model => model.Chapel, "Yes", new {id="Yes", @class = "styled", htmlAttributes = new { @checked = "true"} })
      Yes
    </label>
    <label class="radio-inline">
      @Html.RadioButtonFor(model => model.Chapel, "No", new {id="No", @class = "styled", htmlAttributes = new { @checked = "true" } })
      No
    </label>
    @Html.ValidationMessageFor(model => model.Chapel, "", new { @class = "text-danger" })
  </div>
</div>

渲染的 HTML

<label class="radio-inline">
<div class="choice" id="uniform-No"><span class="checked"><input checked="checked" class="styled" htmlattributes="{ checked = true }" id="No" name="Chapel" type="radio" value="No" autocomplete="off"></span></div>
                                            No
</label>


<input class="styled" htmlattributes="{ checked = true }" id="Yes" name="Chapel" type="radio" value="Yes" autocomplete="off">

标签: javascriptjquery

解决方案


您需要在表单提交时执行此操作,您当前正在设置文档加载和输入点击所需的属性。像这样实现:

$('form').submit(function(e)
{
    e.preventDefault(); //stop form submitting straight away

    var radio = $('.my-radio');

    if (radio.val() === 'foo') {
        //disable require msg e.g. (this is an example - not a copy + paste)
        $('form input').each(function()
        {
            $(this).removeAttr('required')
        })
    }

    $(this).submit()
})

参考:

https://api.jquery.com/removeAttr/


推荐阅读