Как проверить динамически сгенерированную группу переключателей, используя jquery ненавязчиво и Asp. Net Mvc? - PullRequest
0 голосов
/ 16 января 2020

Я разрабатываю приложение для опроса, используя Asp. Net Mvc. Я в конце проекта, но у меня есть проблема. Клиент, имеющий ссылку на опрос, входит в ссылку и видит интервью. Вопросы в анкете и их варианты создаются динамически. Другая опция некоторых вопросов может заполнять одно текстовое поле для каждого вопроса. Клиент, который будет голосовать за вопросник, должен проголосовать за все вопросы с помощью переключателя. Как я уже сказал, в некоторых вопросах опция «Другое» активирует текстовое поле и вводит текст здесь. Клиент, отправляющий голос, отправляет опрос. При отправке на все вопросы необходимо ответить. Как я могу сделать это, используя javascript ненавязчивый. Должен ли я определить правило? Я не знаком с Javascript ненавязчивым. Я жду вашей помощи, бросая кусочки примера кода.

Форма

 @using (Html.BeginForm("SubmitSurvey", "Survey", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Token)           
        <div class="card">
            <div class="card-header bg-gradient-blue "><span class="badge badge-warning"><i class="fa fa-server"></i></span><b> @Model.SurveyName</b></div>
            <div class="card-body" style="overflow-y: auto; max-height: 100%" id="questionList">
                @{ int i = 0; }
                @foreach (SurveyQuestions surveyQuestion in Model.SurveyQuestions)
                {
                    <div class="card" style="margin-bottom: 5px">
                        <div class="card-header bg-gradient-blue"><span class="badge badge-warning">Question @(++i).</span> @surveyQuestion.Questions.QuestionName</div>
                        <div class="card-body" id="questionPortlet">
                            @foreach (Options option in surveyQuestion.Questions.Options)
                            {
                                <div class="custom-control custom-radio">
                                    @Html.RadioButton("optionRadioButton-" + option.QuestionId, "option_" + option.QuestionId + "_" + option.OptionId, new { id = "option_" + option.QuestionId + "_" + option.OptionId, @class = "custom-control-input" })
                                    @Html.Label("option_" + option.QuestionId + "_" + option.OptionId, option.OptionName, new { @class = "custom-control-label font-weight-lighter" })
                                </div>
                            }
                            @if (surveyQuestion.Questions.IsOtherOptionRequired)
                            {
                                <div class="form-group" id="optionOtherParent">
                                    <div class="custom-control custom-radio">
                                        @Html.RadioButton("optionRadioButton-" + surveyQuestion.QuestionId, "optionOther_" + surveyQuestion.QuestionId, new { id = "optionOther_" + surveyQuestion.QuestionId, @class = "custom-control-input" })
                                        @Html.Label("optionOther_" + surveyQuestion.QuestionId, "Other", new { @class = "custom-control-label font-weight-lighter" })
                                    </div>
                                    @Html.TextArea("optionOtherText-" + @surveyQuestion.Questions.QuestionId, "", new { @class = "form-control", rows = "3", id = "optionOtherText_" + surveyQuestion.QuestionId, disabled = "disabled" })
                                </div>
                            }

                        </div>
                    </div>
                }
            </div>

            <div class="card-footer bg-primary d-flex justify-content-end">
                <button type="submit" class="btn btn-warning" style="margin-bottom: 3px; margin-left: 5px; color: black"><i class="fa fa-save"></i>Send Survey</button>
            </div>
        </div>
                    }

Сгенерированный html код выше

  <div class="card" style="margin-bottom: 5px">
                        <div class="card-header bg-gradient-blue"><span class="badge badge-warning">Question 2.</span> Merinosun hangi modellerini begeniyorsunuz?</div>
                        <div class="card-body" id="questionPortlet">
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2017" name="optionRadioButton-4" type="radio" value="option_4_2017" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2017">Model 1</label>


                                </div>
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2018" name="optionRadioButton-4" type="radio" value="option_4_2018" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2018">Model 2</label>


                                </div>
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2019" name="optionRadioButton-4" type="radio" value="option_4_2019" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2019">Model 3</label>


                                </div>
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2020" name="optionRadioButton-4" type="radio" value="option_4_2020" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2020">Model 4</label>


                                </div>
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2021" name="optionRadioButton-4" type="radio" value="option_4_2021" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2021">Model 5</label>


                                </div>
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2022" name="optionRadioButton-4" type="radio" value="option_4_2022" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2022">Model 6</label>


                                </div>

                        </div>
                    </div>

Отредактировано

Как преобразовать подписки в ненавязчивую проверку

$(document).ready(function(){
$('#radioValidate').click(function(){
    var check = true;
    $("input:radio").each(function(){
        var name = $(this).attr("name");
        if($("input:radio[name="+name+"]:checked").length == 0){
            check = false;
        }
    });

    if(check){
        alert('One radio in each group is checked.');
    }else{
        alert('Please select one option in each question.');
    }
});
});

enter code here

1 Ответ

0 голосов
/ 16 января 2020

Вы можете попытаться вручную добавить правила к своим кнопкам.

   $yourButtonSelector.rules('add', 'required');
   $yourFormSelector.validate();

   if (!$yourFormSelector.valid()) {
         return;
   }

Не забудьте импортировать jQuery проверочные сценарии!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...