简体   繁体   中英

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. I want to dynamically set, that when user give result less than 3 on question comment on this question become the required. On other side, when user give result the better like mark 3 comment on this question is not required.

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');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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