jquery AJAX 脚本成功完成后,以编程方式将 Bootstrap 复选框切换为OFF

k5hmc34c  于 2023-02-08  发布在  jQuery
关注(0)|答案(1)|浏览(86)

我有一个HTML表单,它在员工屏幕上包含一个Bootstrap复选框开关。它隐藏了更改密码的字段。当您单击它时,它会显示这些字段。(再次单击它,它会再次隐藏这些字段。)
我想做的是,当更新数据库中Employee记录的AJAX脚本返回SUCCESS时,将其更改为"off",以便用户可以看到保存已经完成。
我有这个:

var formData = $("#employeeForm").serialize();

$.ajax({
  type: "POST",
  url: "/Employee/SaveEmployee",
  data: formData,
  success: function(result) {
    $("#PasswordChange").prop("checked", false);
    $("#PasswordChange").click();
    // Process the result of the AJAX call
    // For example, you can show a success message or redirect to another page
  },
  error: function(xhr, ajaxOptions, thrownError) {
    // Handle the error
  }
});

但是它不起作用。我知道AJAX在起作用,因为数据库中的值在变化。
x一个一个一个一个x一个一个二个x

5f0d552i

5f0d552i1#

问题是你在ajax回调中做的两件事有一些重叠,第一件事把复选框设置为off,但是点击触发器又把它设置回true,只要点击就行了。

$('#PasswordChange').change(function() {
  if (this.checked) {
    $(this).val(true);
    $("#hiddenFields").show();
  } else {
    $(this).val(false);
    $("#hiddenFields").hide();
  }
});

setTimeout(() => {
  $("#PasswordChange").click();
}, 3000);
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<div class="container">
  <p>Toggle the checkbox inside three seconds.</p>

  <div class="form-group row">
    <div class="form-check form-switch col-4 align-with-label">
      <input class="form-check-input" type="checkbox" value="false" id="PasswordChange" name="PasswordChange">
      <label class="form-check-label" for="PasswordChange">Change Password</label>
    </div>
  </div>

  <!-- Hidden Rows for changing password-->
  <div class="form-group row" id="hiddenFields" style="display: none;">
    <div class="col-md-10 offset-md-1">
      <div class="row justify-content-start">
        <div class="col-4">
          <label>Old Password</label>
        </div>

        <div class="col-4">
          <label>New Password</label>
        </div>

        <div class="col-4">
          <label>Reenter New Pwd</label>
        </div>
      </div>

      <div class="row justify-content-start">
        <div class="col-4">
          <input type="text" id="Password" name="Password" class="form-control" value="">
        </div>

        <div class="col-4">
          <input type="text" id="NPassword1" name="NPassword1" class="form-control" value="">
        </div>

        <div class="col-4">
          <input type="text" id="NPassword2" name="NPassword2" class="form-control" value="">
        </div>
      </div>
    </div>
  </div>

  <div class="row offset-md-3">
    <div class="col-4">
      <button class="button button-sel" id="savebutton" name="savebutton" type="submit">SAVE</button>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

相关问题