jquery 调用Javascript函数后提交按钮不工作

gtlvzcf8  于 2023-03-17  发布在  jQuery
关注(0)|答案(1)|浏览(122)

我在我的cshmtl页面上有以下代码。我有一个复选框问用户一个问题,并根据该问题,我要求用户填写一个文本框,所以我使一个文本框所需的。下面是我的代码:

@{
    ViewData["Title"] = "Home Page";
}

<form asp-action="Create">

    <input type="checkbox" id="FirstBox" />Is this test?
    <br />
    <input id="test1" class="form-control" />    <br />
    <input id="test2"   class="form-control" />
    <span id="lblMessage" style="display: none; color: red;">Please fill out at least one text box</span>
    <br />
    <button type="submit" id="myBtn1" onclick="Validate();return false;">Submit</button>

</form>


@section scripts {
    <script type="text/javascript">
        function Validate() {
            var message = document.getElementById("lblMessage");a
            message.style.display = "none";
            var fb = document.getElementById("FirstBox");
            var sb = document.getElementById("test1");
            var tb = document.getElementById("test2");
            if (fb.checked) {
                if (fb.checked) {
                    if (sb.value == "" && tb.value == "")
                    message.style.display = "block";
                }
            }
        }
       
    </script>
}

在提交按钮上调用Validate函数后,提交按钮停止响应。2它停止重定向到另一个页面。3如果我从提交按钮上删除Validate()函数,它就开始工作了。4下面是我的控制器代码:

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create()
        {
            return RedirectToAction("Index", "Employee");
        }

下面是我的应用程序的屏幕截图:

以下是员工控制器代码:

namespace WebApplication3.Controllers
{
    public class EmployeeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

任何帮助都将不胜感激。

h7appiyu

h7appiyu1#

您可以使用一个变量来跟踪表单是否有效,并根据它返回true/false来提交表单。

演示代码

function Validate() {
  var flag = true; // added this variable
  var message = document.getElementById("lblMessage");
  message.style.display = "none";
  var fb = document.getElementById("FirstBox");
  var sb = document.getElementById("test1");
  var tb = document.getElementById("test2");
  if (fb.checked) {
    if (sb.value == "" && tb.value == "") {
      message.style.display = "block";
      flag = false; //added false if found empty
    }
  }
  return flag; //return true/false..
}
<form asp-action="Create">

  <input type="checkbox" id="FirstBox" />Is this test?
  <br />
  <input id="test1" class="form-control" /> <br />
  <input id="test2" class="form-control" />
  <span id="lblMessage" style="display: none; color: red;">Please fill out at least one text box</span>
  <br />
  <button type="submit" id="myBtn1" onclick="return Validate();">Submit</button>
  <!--added return here -->

</form>

相关问题