0

I have a html page with a dynamic section that changes depending on the options selected. Here´s options part:

<div class="form-group-lg">
                        @foreach (var respuesta in Model.ListRespuestas) {
                            <div class="col-md-8">
                                <label class="control-label" for="@respuesta.Id">
                                    @respuesta.Nombre
                                </label>
                                <input type="radio" name="SelectedItem" id="@respuesta.Id" value="@respuesta.Id" style="margin-right: 10px;" />
                            </div>
                        }
                    </div>

This changes when the "next" ("siguiente" for non spanish speakers) button is pressed. This is the code for the button:

<div class="col-md-6 text-right">
                    <span data-placement="top" data-toggle="tooltip" title="" data-original-title="Confirmación de acción">
                        <input type="submit" id="siguiente" class="btn btn-primary" value="Siguiente" />
                    </span>
                </div>

And this button is scripted here:

<script>
            $('#siguiente').click(function (e) {
                e.preventDefault();
                SendAjaxForm();
            });
            $('input:radio[name="SelectedItem"]').change(
                function () {
                    if (this.checked) {
                        $.post('@Url.Content("~/Home/Opciones/?idrespuesta=")' + this.id, function (data) {
                            $("#content-options").html(data);
                        });
                    }
                });
        </script>

All of this works fine. The page displays the first question, then the user chooses one and clicks next, then the frame changes and displays the correspondent next questions and the process goes on until it finishes the question branch.

However, I can't work out how to code the button to throw a warning message when clicked and no option is selected (the tricky part is the none selected behavior, I know how to throw exceptions). Any help (including docs or wikis) are welcome. Thanks everyone in advance.

EDIT - UPDATE

So I've updated the button script

<script>
            $('#siguiente').click(function (e) {
                if ($('input:radio[name="SelectedItem"]').is(':checked')){
                    e.preventDefault();
                    SendAjaxForm();

                    $('input:radio[name="SelectedItem"]').change(function () {
                        if (this.checked) {
                            $.post('@Url.Content("~/Home/Opciones/?idrespuesta=")' + this.id, function (data) {
                                $("#content-options").html(data);
                            });
                        }
                    });
                } else {
                    alert("No se ha seleccionado nada");
                }
            });

        </script>

And now I show an alert message when no option is selected, but the "SendAjaxForm" function still gets executed - generating an exception (reference to null parameter while expecting int because the field "idrespuesta" is null, no option selected). Don't know why. Anyway thanks everyone.

dCarMal
  • 151
  • 7
  • If you had generated you view correctly by binding to a model with the strong typed `HtmlHelper` methods, then that would all be done out of the box, But you can always check if `resp` is `undefined` –  Aug 28 '18 at 10:38
  • @StephenMuecke I actually received this unfinished project as a part of my learning, can you please provide a reference/link so I can read about those HtmlHelper methods in detail? Thank you and thanks for your answer. – dCarMal Aug 28 '18 at 10:43
  • You code for generating the radio buttons in the loop would be `` and after the loop add `@Html.ValidationMessageFor(m => m.SelectedItem)`, where the property is `[Required]public int? SelectedItem { get; set; }` –  Aug 28 '18 at 11:04
  • The you would re-parse the `$.validator` when adding the content - refer [this answer](https://stackoverflow.com/questions/31768946/required-field-validations-not-working-in-jquery-popup-mvc-4/31769058#31769058). Then you handle the forms `.submit()` event and check `.valid()`, and if not cancel the ajax (and the error message will be displayed) –  Aug 28 '18 at 11:07
  • @StephenMuecke Thanks for your answer. The changes you propose exceeds my current C# knowledge (not because I don't understand it, seems to be a proper structure/design issue), but I'll give a good look into it. If you can point me how to search about it that'll be great. Thanks again. – dCarMal Aug 28 '18 at 11:47

1 Answers1

0

I finally got it. The proposed changes affect only the script:

<script>
$('#siguiente').click(function (e) {

    $('input:radio[name="SelectedItem"]').change(function () {
        if (this.checked) {
            $.post('@Url.Content("~/Home/Opciones/?idrespuesta=")' + this.id, function (data) {
                $("#content-options").html(data);
            });
        }
    });

    if ($('input:radio[name="SelectedItem"]').is(':checked')){
        e.preventDefault();
        SendAjaxForm();

    } else {
        e.preventDefault();
        alert("No se ha seleccionado nada");
        }
});</script>

Explanation

With the if... else inserted on the click function we check if any option is selected:

if ($('input:radio[name="SelectedItem"]').is(':checked')){
        e.preventDefault();
        SendAjaxForm();

    } else {
        e.preventDefault();
        alert("No se ha seleccionado nada");
        }

Notice the lines e.preventDefault(); on both if... else alternatives. This was to prevent the button from still working even if there's no option checked.

Now, if we press the "next" button without any option checked, shows an alert and stays on the page until any option is previously selected. Thanks everyone for your support, I hope this helps.

Happy coding.

dCarMal
  • 151
  • 7