I have the following html:
<div class="form-outline mb-4"> <input type="text" id="PlanID" asp-for="PlanID" name="PlanID" class="form-control form-control-lg" value="@Model.PlanID" /> <label id="errorLabel" name="errorLabel" class="form-label text-danger" for="PlanID"></label> </div> <button class="btn btn-primary btn-lg btn-block" type="button" disabled id="nextButton" name="nextButton" onclick="DisplayProgressMessage(this, 'Next');">Next</button>
And I have the following jquery:
$.ajax({ type: "POST", url: "@Url.Action("CheckPlanID")", data: {PlanID: planID}, dataType: "text", success: function (msg) { if (msg.length > 4) { console.log(msg.length); $("#nextButton").prop("disabled", true); $("#errorLabel").text = msg; } }, error: function (req, status, error) { console.log(msg); } });
I have additional jquery that keeps the button disabled until the length of the data in the input is 4. When the length is 4, I enable the button.
When running the code, as soon as the length of the data in the input box is 4, the button is enabled and I click on it. the ajax executes and sends the data to my controller. The controller processes the data and will send back a string. If the length of the returned string is greater than 4, then the string being returned is an error string and that error string should get displayed to the user.
When I run the code and force an error, I can see the length of the error string being displayed in the console so I know this section of code is being executed. The button gets disabled, but the text of the errorLabel is not changing.
The text of the errorLabel should change to the error message. Is there something else that needs to be done? Am I missing something?
Thank you!
Advertisement
Answer
In jQuery
, text
is a method not an attribute so to fix your issue you’d simply change this
$("#errorLabel").text = msg
into this
$("#errorLabel").text(msg)
Also it seems, based on your code if (msg.length > 4)
, you only change the text if msg
length is greater than 4
. That means, unless msg
has 5
characters or more the text won’t change.
Learn more about
text()
method onjQuery
docs.