使用 Jquery 将属性 Required 添加到 Razor 应用程序中的输入中

Adding the attribute Required to an input within Razor application with Jquery

本文关键字:应用程序 Razor 输入 添加 Jquery 属性 Required 使用      更新时间:2023-09-26

我有一个 asp.net 的MVC4应用程序,其中我有这个形式:

  <form method="Post" action="/User/Validate_Expert_Decision" target="_parent">
      <span>
          <b style="color:red" >Votre avis</b>
          <br />
          <br />
          <input type="radio" name="avis" value="1" checked>Validé &nbsp &nbsp &nbsp &nbsp
          <input type="radio" name="avis" value="2">Refusé &nbsp &nbsp &nbsp &nbsp
          <input type="radio" name="avis" value="3">Demande de spécification &nbsp &nbsp &nbsp &nbsp
          <input type="radio" name="avis" value="4">Demande d'analyse 
          <br />
          <br />
          <br />
      </span>
    <span>
        <b style="color:red" >
        Votre justification * 
        <b />
          <br />
          <br />
      <textarea rows="16" cols="75" name="justification"></textarea>
    </span>
    <input type="hidden" name="elem" value="0"  id="elem"/>
    <p> 
      <input type="submit" name="submit">
      <input type="button" name="cancel" value="Annuler" onClick="closebox()">
    </p>
  </form>

我需要将属性required添加到文本区域justification当单选按钮将 2、3 或 4 作为值时,即仅对于第一个不需要justification输入的值。

那么,我该如何完成此任务?

<script>
    $(document).ready(function () {
        $('input[name="avis"]').change(function () {
            var t = $('textarea[name="justification"]');
            if ($(this).val() != 1)
                t.attr('required', 'required');
            else
                t.removeAttr('required');
        })
    })
</script>

有这样的事情吗?

$("input[name='avis']").on("change", function () {
    var value = $(this).val();
    $('td[name=justification]').prop("required", value != "1");
});