简体   繁体   English

jQuery 在 ajax 之后不更改元素文本

[英]jQuery does not change element text after ajax

I have the following html:我有以下 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:我有以下 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.我还有额外的 jquery 使按钮保持禁用状态,直到输入中的数据长度为 4。当长度为 4 时,我启用按钮。

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.运行代码时,只要输入框中的数据长度为4,按钮就被启用,我点击它。 the ajax executes and sends the data to my controller. ajax 执行并将数据发送到我的 controller。 The controller processes the data and will send back a string. controller 处理数据并将返回一个字符串。 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.如果返回字符串的长度大于 4,则返回的字符串是错误字符串,并且该错误字符串应该显示给用户。

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.该按钮被禁用,但 errorLabel 的文本没有改变。

The text of the errorLabel should change to the error message. errorLabel 的文本应更改为错误消息。 Is there something else that needs to be done?还有什么需要做的吗? Am I missing something?我错过了什么吗?

Thank you!谢谢!

In jQuery , text is a method not an attribute so to fix your issue you'd simply change thisjQuery中, text是一种方法而不是属性,因此要解决您的问题,您只需更改它

$("#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 .此外,根据您的代码if (msg.length > 4) ,您似乎只在msg长度大于4时更改文本。 That means, unless msg has 5 characters or more the text won't change.这意味着,除非msg5或更多字符,否则文本不会改变。

Learn more about text() method on jQuery docs.jQuery文档上了解有关text()方法的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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