首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当我在警报提示符中单击“否”时,切换切换返回到以前的状态

当我在警报提示符中单击“否”时,切换切换返回到以前的状态
EN

Stack Overflow用户
提问于 2019-11-23 16:10:05
回答 4查看 2.7K关注 0票数 1

我创建了一个开关开关,允许系统管理员激活/禁用帐户的登录访问。

当管理员单击开关切换(开关从状态1移动到0)后,它将通过警报框提示确认(您想激活/停用此帐户吗?是的,当我单击"no“时,我希望它返回到以前的状态(从0到1)。

如果状态为" 1“帐户被激活,我成功地做到了这一点,但是当它反过来,从状态0到状态1,开关切换就不会返回到以前的状态,并被困在状态1。

它仍然发送正确的POST命令tho (例如,如果帐户被激活,则关闭帐户,反之亦然),但是可视化显示是错误的。

这是我的密码。

切换开关的Javascript

代码语言:javascript
复制
var chk;
    $(document).on('change', '.btn-change-status', function(e) {
      e.preventDefault();
      chk = $(this);
      var switch_status = $(this).attr('data-status');
      var account_status = (switch_status == 1) ? 0 : 1;
      var id  = $(this).attr('data-id');
      var confirm_alert = (switch_status == 1) ? confirm("Are you sure you want to deactivate this account?") : confirm("Are you sure you want to activate this account?");
        if (confirm_alert == true) {
         $.ajax({
              url: "/user/update-status",
              type: "POST",
              data: {
                _token: "{{csrf_token()}}",
                id: id,
                status: account_status
              },
              success: function(data) {
                if (data.success === true) {
                  alert("Account Successfully Updated!");
                  location.reload();
                }
              }

            });
        }
        else {
          if(chk.checked) {
            chk.prop("checked", false);
          }
          else {
            chk.prop("checked", true);
          }
        }
    });

编辑:添加了开关的HTML部分,尽管它仍然在javascript中,因为我把它附加到了dataTable上。

dataTable的HTML

代码语言:javascript
复制
 <div class="card mb-3">
            <div class="card-header">
              <i class="fas fa-table"></i>
              Accounts Management</div>
            <div class="card-body">

              <button type="button" id="btn-add-account" class="btn btn-primary">Add Account</button>
              <div class="table-responsive mt-3">
                <table class="table table-bordered dt-responsive" id="table-accounts" width="100%" cellspacing="0">
                  <thead>
                    <tr>
                      <th class="hidden">ID</th>
                      <th>Username</th>
                      <th>Email</th>
                      <th>Role</th>
                      <th>Date Created</th>
                      <th style="width: 15.5%">Actions</th>
                    </tr>
                  </thead>
                  <tfoot>
                    <tr>
                      <th class="hidden">ID</th>
                      <th>Username</th>
                      <th>Email</th>
                      <th>Role</th>
                      <th>Date Created</th>
                      <th style="width: 15.5%">Actions</th>
                    </tr>
                  </tfoot>
                  <tbody>
                  </tbody>
                </table>
              </div>
            </div>
          </div>

        </div>
        <!-- /.container-fluid -->
      </div>

dataTable Javascript

代码语言:javascript
复制
$(document).ready(function() {
    getRoles();
    var accounts;
     $('#account-management').addClass('active');

    accounts = $("#table-accounts").DataTable({
        ajax: {
          url: "/users/get-all-users",
          dataSrc: ''
        },
        responsive:true,
        "order": [[ 7, "desc" ]],
        columns: [
        { data: 'id'},
        { data: 'username' },
        { data: 'email'},
        { data: 'role.id'},
        { data: 'created_at'},
        { data: null,
          render: function ( data, type, row ) {
            var html = "";
            if (data.status == 1) {
              html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'" checked> <label for="'+data.id+'"></label></span>';
            } else {
              html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'"> <label for="'+data.id+'"></label></span>';
            }
              html += "<button type='button' class='btn btn-primary btn-sm btn-edit-account mr-2' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>";
              html += "<button type='button' class='btn btn-secondary btn-sm btn-reset-password' data-id='"+data.id+"' data-account='"+data.id+"'><i class='fas fa-key'></i></button>";

            // <button type='button' class='btn btn-primary btn-sm btn-edit' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button> 
            // html += "<button class='btn btn-danger btn-sm btn-delete' data-id='"+data.id+"' data-account='"+data.id+"'>Remove</button>";

            return html;
          } 
        },
        ],
        columnDefs: [
        { className: "hidden", "targets": [0]},
         { "orderable": false, "targets": 4 }
        ]
    });

谢谢!

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-11-24 01:09:15

有太多的值代表着相同的东西。您只需要两个值:

checkbox.

  • status:类型的
  1. id:
  2. 类型的字符串id:默认情况下,复选框值为true,如果选中,则为false

在这种情况下,您不需要任何data-*属性,但是如果您仍然认为需要使用.data()方法,则使用以下方法:

代码语言:javascript
复制
$('.status').data('id') // Returns the value of `data-id` on each `input.status`

如果出于某种原因,您发现您需要在这样一个琐碎的任务中使用更多的值,则需要从根本上重新评估您的代码。详细信息在演示中有注释,它使用一个实时测试服务器来验证发送给它的内容。

代码语言:javascript
复制
/* This function extracts the value of each output.member and then assigns a 
   modified version of the value as the id of the checkbox that follows (input.status)
   This is not required to answer the OP's question and is intended just to provide each
   checkbox with a unique id */
$('.member').each(function(index) {
  let user = $(this).val().split('@')
  let id = user[0] + '-' + index;
  $(this).next('.status').attr('id', id);
});

// Any change event occuring on any input.staus (checkbox)...
$('.status').on('change', function(e) {

  // A boolean that reflects the checkbox "check status"
  let checked = $(this).is(':checked');
  
  // A simple confirm...
  let changed = confirm("Are you sure you want to change this account?");
  
  //... if user cancels...
  if (!changed) {
  
    /* ...ternary: [?][if checkbox is checked] - [uncheck it] [:][otherwise] - [check it]
    [return][Terminate function - don't do anything else] */
    return checked ? $(this).prop('checked', false) : $(this).prop('checked', true);
  }
  
  /* function continues here if user confirmed by clicking "OK"
     The data will be posted to a live test server.
     A link will appear at the bottom, follow the directions to verify response */
  let ID = this.id;
  let active = checked ? 1 : 0;
  $.ajax({
    url: "http://ptsv2.com/t/status/post",
    type: "POST",
    data: {
      id: ID,
      status: active
    },
     success: function() {
       $('.response').show();
    }
  });
});
代码语言:javascript
复制
:root {
  font: 16px/1 Arial
}

label {
  display: block;
  margin: 8px 0 0 0;
}

.member {
  display: inline-block;
  width: 25ch;
  vertical-align: middle
}

.status {
  display: inline-block;
  vertical-align: middle
}

.response {
  display: none;
  cursor: pointer;
  width: 99vw
}

.response * {
  display: block;
  margin: 8px auto;
  width: 90%
}
代码语言:javascript
复制
<form id='admin-panel'>
  <fieldset class='member-status'>
    <legend>Member Status</legend>
    <label>
    <output class='member'>zer00ne@gmail.com</output>
    Status: <input class='status' type='checkbox' checked>
    </label>
    <label>
    <output class='member'>tech.artificer@gmail.com</output>
    Status: <input class='status' type='checkbox' checked>
    </label>
    <label>
    <output class='member'>joker666@4chan.org</output>
    Status: <input class='status' type='checkbox'>
    </label>
    <label>
    <output class='member'>byte.my@ss.com</output>
    Status: <input class='status' type='checkbox' checked>
    </label>
    <label>
    <output class='member'>bruce@wayne.com</output>
    Status: <input class='status' type='checkbox' checked>
    </label>
    <label>
    <output class='member'>clark.kent@dailyplanet.com</output>
    Status: <input class='status' type='checkbox' checked>
    </label>
  </fieldset>
  <hr>
  <output class='response'>
    <a href="https://ptsv2.com/t/status/d/latest" target='view'>Click then scroll down to <i style='display:inline'>Parameters</i> inside the iframe below</a>
    <iframe name='view'></iframe>
  </output>

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

票数 0
EN

Stack Overflow用户

发布于 2019-11-23 17:12:10

你能用你的HTML更新你的文章吗?因为我不确定问题中描述的情况。我知道为什么代码不能工作,但需要查看HTML来进一步调查。事后看来,我意识到我的解决方案可能并没有解决这个问题。

如果类btn-change-status的元素是<button>标记,那么jQuery的.on("change", handler)将无法工作( handler是您的函数)。根据jQuery文档:

当元素的值发生变化时,change事件被发送到元素。此事件仅限于<input>元素、<textarea>框和<select>元素。

相反,我建议使用以下方法之一:

  • .on("click", handler)
  • .on("mouseup", handler)
  • .on("mousedown", handler)

看看哪个管用。

票数 0
EN

Stack Overflow用户

发布于 2019-11-23 17:43:40

因为您使用的是类选择器“..btn change”

代码语言:javascript
复制
chk = $(this);

chk现在是一个包含1元素的集合。若要检查是否已选中,请使用

代码语言:javascript
复制
chk.prop('checked')

代码语言:javascript
复制
chk[0].checked
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59009566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档