简体   繁体   English

使用jQuery在ASP.NET MVC剃须刀中设置表单的必需项

[英]Set required item of form in asp.net mvc razor with jQuery

I have this problem: I created feedback form (in form is question, then result(radio buttons from 1 to 5) and comment), this feedback has many question, which are loaded from database table questions. 我有这个问题:我创建了反馈表单(表单是问题,然后是result(单选按钮,从1到5)和注释),此反馈有很多问题,是从数据库表问题中加载的。 I want to dynamically set, that when user give result less than 3 on question comment on this question become the required. 我想动态设置,当用户对该问题的评论给出的结果小于3时,就成为必需项。 On other side, when user give result the better like mark 3 comment on this question is not required. 另一方面,当用户给出结果更好的标记3时,不需要对此问题进行评论。

This is my feedback form: 这是我的反馈表:

@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()

  <div class="form-horizontal">
    @foreach (var item in Model)
    {
    <div class="form-group" style="text-align:center;">
      <h2>  @Html.Label(item.questions.question) </h2>
        <div class="col-md-10">
            <label class="radio-inline">@Html.RadioButton(item.question_id.ToString(), 1) 1 </label>
            <label class="radio-inline">@Html.RadioButton(item.question_id.ToString(), 2) 2 </label>
            <label class="radio-inline">@Html.RadioButton(item.question_id.ToString(), 3) 3 </label>
            <label class="radio-inline">@Html.RadioButton(item.question_id.ToString(), 4) 4 </label>
            <label class="radio-inline">@Html.RadioButton(item.question_id.ToString(), 5) 5 </label>
        </div>
        <div class="col col-md-10">
            <label>comment: @Html.TextArea(item.question_id.ToString() + "_comment", new { @class = "form-control", @cols = 200, @rows=5 }) </label>
        </div>
    </div>
    <hr>
    }
   <input type="hidden" name="feedback_id" value="@ViewBag.feedback_id">
    <div class="form-group">
        <div class="col-md-12" style="margin-left:330px;">
            <input type="submit" value="Send" class="btn btn-primary btn-block" />
        </div>
    </div>
  </div>
}

I assume that what you want is a client-side validation: 我假设您想要的是客户端验证:

$('.radio-inline').change(function() {
    var commentQuestionName = $(this).attr('name') + '_comment';
    if ($(this).val() < 3) {
        $('input[name="' + commentQuestioName + '"]').show();
    }
    else {
        $('input[name="' + commentQuestioName + '"]').hidden();
    }
});

Try like following code snippet. 尝试像下面的代码片段。 Hope this will help you. 希望这会帮助你。

$('.radio-inline > input').change(function() {
    var val = $(this).val();
    var comment = $(this).closest('.form-group').find('textarea.form-control');
    if (val < 3) {
        comment.attr('required', 'required');
    }
    else {
        comment.removeAttr('required');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM