我幫你把程式碼重構過了(大致上)
你應該要的是「我想同時共用表單在編輯和新增畫面,然後某些表單才需要密碼欄位(像是新增畫面)」,如下圖:
這部分我幫你寫出來了,你可以參考一下我的邏輯,我將畫面上的元素建立了一個.dymanic-display的css class,然後動態控制其顯示,例如當我在編輯畫面我就不顯示,以上
再來我將 html 和 javascript「分離」,兩邊都是存粹的,不要讓程式碼混雜在一起(義大利麵),這嚴重不利於維護和他人閱讀,我光是要看懂你在幹什麼就花了一個小時。
接著你的變數命名風格可以統一,不要一下 SelectToken 一下 select_token,這也造成嚴重的閱讀困擾。
然後你的HTML在Head中有多個標籤重複宣告,在Body中有無意義的標籤和javascript程式碼,請避免再發問的時候將亂七八糟的東西提交出來,至少整理一下。
另外你在js中的getToken可以共用,你不需要每次都重新取得用戶的token。
以及程式碼請套formatter不管怎樣程式碼要縮排,閱讀性比較佳。
然後下面這段不要混用,擇一就好,不要弄到到處都是(到處都是入口很亂)
$(document).ready(() => {});
(function() { })();
再來程式碼註解寫清楚,不要有寫跟沒寫一樣
像是 「// need to add api Authorization in header」
我光看code就知道你這行用意了,你只是畫蛇添足而已,好的程式碼不需要特別寫註解就很好理解,請你先改善你的變數命名方式,可參閱負面代碼書寫準則(反面教材)
以下是完成品:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Account Management</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
</head>
<body>
<h1>Account Management</h1>
<main id="main-holder"></main>
<div id="app"></div>
<table id="example" class="display"></table>
<div class="table-title">
<div class="row">
<div class="col-sm-4">
<button type="button" id="AddedNew_Data" class="btn btn-primary" data-toggle="modal"
data-target="#exampleModal">Add New User</button>
</div>
</div>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">device_id:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="input_edit_device_id" class="col-form-label">Login ID:</label>
<input type="text" class="form-control" id="input_edit_userid">
</div>
<div class="form-group">
<label for="input_edit_name" class="col-form-label">Name:</label>
<input type="text" class="form-control" id="input_edit_name">
</div>
<div class="form-group">
<label for="field1" class="col-form-label">Account Type:</label>
<input type="text" class="form-control" id="input_edit_acc_type">
</div>
<div class="form-group">
<label for="field1" class="col-form-label">Active:</label>
<input type="text" class="form-control" id="input_edit_active">
</div>
<div class="dymanic-show">
<div class="form-group">
<label for="field1" class="col-form-label">New Account password:</label>
<input type="text" class="form-control" id="input_add_password">
</div>
<div class="form-group">
<label for="field1" class="col-form-label">New Account password confirm:</label>
<input type="text" class="form-control" id="input_add_password_confirm">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="save()">Send message</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.4.0/axios.min.js"
integrity="sha512-uMtXmF28A2Ab/JJO2t/vYhlaa/3ahUOgj1Zf27M5rOo8/+fcTUVH0/E0ll68njmjrLqOBjXM3V9NiPFL5ywWPQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!-- JavaScript libraries -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
$(document).ready(() => {
// 用戶的Token
const TOKEN = localStorage.getItem("token");
// 意義不明
var storedItem = localStorage.getItem("storedItem") || [];
// API網址
const USER_API_URL = "/fakedata.php"; // "http://192.168.10.01:8000/api/user/info"
let apiAction;
let selectedData;
let table = $("#example")
.DataTable({
ajax: {
url: USER_API_URL,
headers: {
Authorization: "Bearer " + TOKEN,
},
dataSrc: function (response) {
console.log("response.users", response.users);
return response.users;
},
},
columns: [
{
data: null,
title: "ACTION",
render: (data, type, row) => {
return `
<button class="btn btn-primary" type="button" id="Edit_Data" data-toggle="modal" data-target="#exampleModal" data-whatever=" ">Edit</button>
<button class="btn btn-danger delete-btn" id="Delete_Data" data-id="${row.userid}">Delete</button>
`;
},
},
{ data: "userid", title: "Login ID" },
{ data: "name", title: "Name" },
{ data: "acc_type", title: "Account Type" },
{ data: "created_at", title: "Created Time" },
],
})
.draw();
// 表格中的編輯按鈕被點選時,取得該列的資料,並且將apiAction設為edit模式
$("#example tbody").on("click", "button", function (event) {
selectedData = table.row($(this).parents("tr")).data();
apiAction = "edit";
console.log("get selected for edit data", selectedData);
console.log("api action:", apiAction);
});
// 當新增按鈕被點選時,將selectedData設為null,並且將apiAction設為add模式
$("#AddedNew_Data").on("click", (event) => {
selectedData = null;
apiAction = "add";
console.log("get selected for edit data", selectedData);
console.log("api action:", apiAction);
});
// 當 modal 被呼叫顯示時,執行以下動作
$("#exampleModal").on("show.bs.modal", function () {
let modal = $(this);
let inputFields = modal.find(".modal-body input");
// 如果是新增模式,則要顯示密碼輸入欄位,否則隱藏
if (apiAction == "add") {
modal.find(".dymanic-show").show();
// 改標題
modal.find(".modal-title").text("Add User");
} else {
// 隱藏密碼輸入欄位
modal.find(".dymanic-show").hide();
// 改標題
modal.find(".modal-title").text("Edit User");
// 如果是編輯模式,則要將該列的資料填入modal中
var keys = Object.keys(selectedData);
for (var i = 0; i < inputFields.length; i++) {
$(inputFields[i]).val(selectedData[keys[i]]);
}
}
});
// 確認是否刪除
$(document).on("click", ".delete-btn", function (event) {
var id = $(this).data("id");
console.log("GET DLETE ID", id);
confirmDelete(id);
});
// 刪除資料
function deleteUser(id) {
const API_URL = `${USER_API_URL}?userid=${id}`;
$.ajax({
url: API_URL,
type: "DELETE",
headers: {
Authorization: "Bearer " + TOKEN,
},
success: function (response) {
console.log(response);
},
}).then((response) => console.log("response", response));
}
function confirmDelete(id) {
if (confirm("sure to delete?") == true) {
var table = $("#example").DataTable();
var row = table.row($(this).closest("tr"));
deleteUser(id);
if (row.length > 0) {
row.remove().draw();
console.log("Delete row with id:", id);
}
} else {
none;
}
}
function saveUser() {
let data = getFormData();
$.ajax({
url: "http://192.168.10.01:8000/api/user/info/",
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data),
headers: {
Authorization: "Bearer " + TOKEN,
},
beforeSend: function (xhr) {
xhr.setRequestHeader("X-HTTP-Method-Override", "POST");
},
success: function (result) {
console.log("SUCCESS", result);
},
error: function (response) {
console.log("ERROR", response);
},
complete: function (response) {
// 都完成才清理input
$("#input_edit_userid").val("");
$("#input_edit_name").val("");
$("#input_edit_acc_type").val("");
$("#input_edit_active").val("");
},
});
}
function getFormData() {
var userid = document.getElementById("input_edit_userid").value || "";
var name = document.getElementById("input_edit_name").value || "";
var acc_type = document.getElementById("input_edit_acc_type").value || "";
var active = document.getElementById("input_edit_active").value || "";
console.log("userid", userid, typeof userid);
console.log("name", name, typeof name);
console.log("iacc_type", acc_type, typeof acc_type);
console.log("active", active, typeof active);
return {
userid: userid,
name: name,
acc_type: acc_type,
active: active,
};
}
$("#exampleModal").on("show.bs.modal", (e) => {
$(".modalTextInput").val("");
let btn = $(e.relatedTarget); // e.related here is the element that opened the modal, specifically the row button
let id = btn.data("id"); // this is how you get the of any `data` attribute of an element
$(".saveEdit").data("id", id); // then pass it to the button inside the modal
});
$(".saveEdit").on("click", function () {
let id = $(this).data("id"); // the rest is just the same
saveNote(id);
$("#exampleModal").modal("toggle"); // this is to close the modal after clicking the modal button
});
function saveNote(id) {
let text = $(".modalTextInput").val();
$(".recentNote").data("note", text);
console.log($(".recentNote").data("note"));
console.log(text + " --> " + id);
}
function editRow(data) {
console.log("GET TOKEN", TOKEN);
console.log("EDIT=====", data);
$.ajax({
url: "http://192.168.10.01:8000/api/user/info/", /// api change ///
type: "PUT", // aka update or edit
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data),
headers: {
Authorization: "Bearer " + TOKEN, // need to add api Authorization in header
},
success: function (response) {
console.log("SUCCESS", response);
},
error: function (response) {
console.log("ERROR", response);
},
});
}
});
你現在做的是兩種功能
你的癥結點在於想讓這兩種功能共用同一表單
但特定欄位又無法共用
解決辦法:
點擊按鈕必須傳入參數
程式藉由參數判斷是否該顯示/隱藏某些欄位
額外思考:
為什麼各大網站這兩種功能都是分開的?
為什麼現在的註冊幾乎只填email與密碼而已?