-1

I'm trying to display a error message using jQuery while submitting the form, when radio button is selected true and input box is empty, for some reason its failing. Any suggestions are appreciated!

<div class="row col-lg-offset-2 top-buffer">
<h4>
    <strong>
        <span>Is Account Deleted?:</span>
    </strong>
</h4>
            @Html.RadioButtonFor(model => model.IsDeleted, true) @Html.Label("Yes")
            @Html.RadioButtonFor(model => model.IsDeleted, false) @Html.Label("No")

<br>
</div>
<div class="row col-lg-offset-2 top-buffer" id="reason">
    <div class="col-sm-2">
        <b>Reason for Delete:</b>
    </div>
    <div class="col-sm-10">
        @Html.TextBoxFor(model => model.reason, new { @class = "form-control", @id = "reason" })

        <br />
    </div>
    <div class="row col-sm-12">
        <label id="lblErrorMsg" class="has-error" style="color: #BD362F"></label>
    </div>
    <div class="col-sm-4">
        <button type = "submit" id="Next" name="Next" class="btn btn-primary">Next</button>
    </div>
</div>

Script:

<script>
$("#Next").click(function () {
    if ($("input[name='IsDeleted']" === "True" && $("#reason").val(''))) {
        $("#lblErrorMsg").text("Please enter meter number");
    } else {
        $("#lblErrorMsg").text("");
    }
});

Mini Me
  • 27
  • 1
  • 1
  • 3
Pradvaar cruz
  • 281
  • 1
  • 9
  • 21
  • try `true` not True, also is your reason but actually building? – clearshot66 Sep 13 '17 at 19:33
  • Use a conditional validation attribute (refer the comment on your [previous question](https://stackoverflow.com/questions/46181191/hide-display-a-input-field-based-on-value-from-htmlradiobuttonfor-and-make-it-ma)) –  Sep 13 '17 at 20:18
  • @StephenMuecke Thanks for the link, It was really helpful. But i'm trying to perform this validation in the view. which one is better to do? This approach works as well. – Pradvaar cruz Sep 13 '17 at 20:33
  • Your approach is awful. A conditional validation attribute works on both the client and the server (and the server side validation is what is important - client side validation is just a nice bonus but anyone can easily override it). Apply a `[RequiredIf("IsDeleted", true, ErrorMessage = "Please enter meter number")]` to your `reason` property and add `@Html.ValidationMessageFor(m => m.reason)` in the view –  Sep 13 '17 at 20:37

1 Answers1

0

I can't be sure since I don't see full html code but try instead of:

if ($("input[name='IsDeleted']" === "True" && $("#reason").val(''))) {

this:

if ($("input[name='IsDeleted']:checked").val() === "True" && $("#reason").val() == '')

improved answer a bit, but make sure that IsDeleted radio button has Value "True"

pegla
  • 1,866
  • 4
  • 17
  • 20