The stored addresses will get from my-account/get-address-list and calling the following function to get the data:
public function get_address_list(user_id = '')
{
offset = 0;
limit=10;sort = 'id';
order=′AmultipleWhere = '';
code
Related Controller functions:
public function add_address()
{
if (this->ion_auth->logged_in()) {
this->form_validation->set_rules('type', 'Type', 'trim|xss_clean');
//this−this->form_validation->set_rules('name', 'Name', 'trim|xss_clean|required');
this->form_validation->set_rules('alternate_mobile', 'Alternative Mobile', 'trim|numeric|xss_clean');
this->form_validation->set_rules('landmark', 'Landmark', 'trim|xss_clean');
/*
this->form_validation->set_rules('area_name', 'Area', 'trim|xss_clean');
this->form_validation->set_rules('city_id', 'City', 'trim|xss_clean');
this->form_validation->set_rules('state', 'State', 'trim|xss_clean|required');
this->form_validation->set_rules('latitude', 'Latitude', 'trim|xss_clean');
$this->form_validation->set_rules('longitude', 'Longitude', 'trim|xss_clean');
*/
code
Related Model function:
function set_address($data)
{
code
now I want to remake the design by using the popup modal that can call/open in anywhere to allow the user to manage their address instead of the page
here are the requirements:
user can view all stored address with details such as address, tel no., name etc.
user can edit stored address or set to the default address
user can add the new address
user can remove added address, with the confirm alert
if in the "checkout" page, a button "選擇為收貨地址" will be appear and allow the user update the shipping address for once time checkout (only for the current checkout, will not set to default)
Assistant
To remake your address management into a reusable modal popup fulfilling your requirements, here is a detailed step-by-step guide including code snippets, wiring backend and frontend to achieve the features:
Approach Overview:
Modal: Create a reusable modal with a table showing all user addresses.
View Addresses: Fetch addresses via AJAX from my-account/get-address-list.
Add/Edit Address: Show the same form inside the modal for adding or editing an address.
Delete Address: Add a delete button with confirmation alert.
Set Default Address: Provide a button/link to set an address as default.
Checkout scenario: Add a special button "選擇為收貨地址" in checkout with behavior to only set the address for the current order (NOT global default).
Step 1: Build the Address Modal HTML
Place this modal HTML in your main layout or relevant pages (like in footer or page):
html
User
Can you redesign the whole popup modal with new css?
the edit/add address should also a popup modal instead of show after table.
to avoid the styling conflict, please all the prefix new-address-modal to the element class or id.
Also update the ajax function after update the class and id
Assistant
Certainly! I'll redesign the modal flow into two modals:
Address List Modal (#new-address-modal-list) — show address table with actions.
Add/Edit Address Modal (#new-address-modal-edit) — popup modal for add/edit form.
All class/id names will be prefixed with new-address-modal- to avoid styling conflicts.
Complete updated code including HTML, CSS and JS for AJAX integration
1. Modal HTML (two modals)
html
User
Please update your design that support responsive design in pc, mobile and tablet.
Also provide the demo with dummy data
Assistant
Certainly! Below is the fully responsive redesigned paired modals (address list + add/edit) with Bootstrap 5, customized CSS using your prefix new-address-modal-, and a fully functional demo including dummy data loaded via JS (no backend needed for demo). This works well on PC, tablet, and mobile.
1. Full HTML + CSS + JS Demo (self-contained)
Copy and paste this into an empty .html file and open in any modern browser:
html
User
instead of using the table to display all addresses, I want to update the design as the following:
show the details by order: address, name and contact no.
the buttons (編輯、刪除、選擇為收貨地址、設為預設) place to the bottom right
show the status default and selected as 收貨地址 in the top right (e.g. 預設地址\n已選擇為收貨地址)
Assistant
Certainly! I've updated the modal address list design based on your requirements:
No table, use card-like stacked blocks for each address.
Can you provide the full updated code with html, css and js to me?
Assistant
Certainly! Below is the full updated demo including:
Two modals:
Address List modal with card style list per your requested design
Add/Edit modal as a popup form
Responsive CSS for PC/tablet/mobile
Full JS including dummy data and all event handlers
Bootstrap 5 + jQuery CDN included
You can copy all below into an .html file and open in any modern browser to demo.
html
User
Please update the full integrated version separately with your latest design and the previous ajax functions
Assistant
Certainly! Below is the full integrated version, combining your existing AJAX backend functions (paths kept as you provided) with the latest card-style address list modal design and separate add/edit modal.
The main points:
The address list modal uses card layout per your design.
Address data is loaded via AJAX from your backend (my-account/get-address-list).
Add/Edit address form submits to your backend (my-account/add-address and my-account/edit_address).
Delete and set default buttons use your existing AJAX endpoints.
The checkout mode triggers special buttons (選擇為收貨地址) and a callback function onCheckoutAddressSelected.
All classes and IDs are prefixed with new-address-modal- to avoid conflicts.
Included form validation (bootstrap 5 + custom).
Full Code (HTML, CSS, JavaScript)
html
User
I have the following code for update the checkout shipping info:
('#address-name').html(('#edit-address-name-' + id).html());// + ' - ' + ('#edit-address-type-' + id).html());
('#address-full').html(('#edit-address-address-' + id).html());
('#address-mobile').html(('#edit-address-mobile-' + id).html());
('#address_id').val(id);
How can I load that address data and update checkout shipping info in onCheckoutAddressSelected(addressId)
Assistant
You currently use span elements like #edit-address-name-ID, #edit-address-address-ID, #edit-address-mobile-ID in your address table or list to display existing address info, so you manipulate the DOM elements directly when updating checkout info.
Since with the new card-style modal design, you don’t have these span elements anymore, but you do have the full address data available either:
by fetching from existing page elements if you keep them somewhere, or
by making an AJAX call to my-account/get-address-list again filtered by address ID (recommended way).
Recommended approach: Use AJAX in onCheckoutAddressSelected() to fetch full details for the selected address, then update your checkout UI.
Example code for onCheckoutAddressSelected(addressId)
js
function onCheckoutAddressSelected(addressId) {
// fetch the address data via ajax
$.ajax({
url: '<?= base_url("my-account/get-address-list") ?>',
method: 'GET',
data: {
user_id: <?= $this->data['user']->id ?>,
id: addressId,
limit: 1
},
dataType: 'json',
success: function(response) {
if (response.total > 0) {
let addr = response.rows[0];
// Update your checkout DOM elements
// Make sure your checkout page has these IDs or update accordingly
$('#address-name').html(addr.name + (addr.type ? ' - ' + addr.type : ''));
$('#address-full').html(addr.address.replace(/\r?\n/g, '<br>'));
$('#address-mobile').html(addr.mobile);
$('#address_id').val(addr.id);
// Optionally, close the modal here or you can do it inside choose button handler in modal
// $('#new-address-modal-list').modal('hide'); // Bootstrap 4 jQuery way, or
// let modal = bootstrap.Modal.getInstance(document.getElementById('new-address-modal-list'));
// modal.hide();
} else {
alert('無法取得該地址資訊');
}
},
error: function() {
alert('載入地址資訊失敗,請稍後再試');
}
});
}
User
How to modify the newAddressModalLoadAddresses to fill addressCache while rendering for avoid the AJAX call?
Assistant
Great! To avoid an extra AJAX call on address selection, you can cache all the loaded addresses in a JavaScript object when you load them inside newAddressModalLoadAddresses. Then, in onCheckoutAddressSelected(addressId) you simply read from this cache and update your checkout form.
Steps to implement:
1. Declare a global cache object:
Place this at the beginning of your JS (within your jQuery ready function or global script):
js
var addressCache = {};
2. Modify newAddressModalLoadAddresses to fill addressCache
When the addresses list is fetched via AJAX (your existing function), after getting the rows, populate this object mapping address id to the address data object.
Example adapted for your code:
js
User
please update the buttons css without using the default btn class
Assistant
Certainly! Below is the updated CSS for your action buttons without using Bootstrap's default .btn classes but retaining Bootstrap's color palettes and hover effects. All buttons will have custom classes prefixed with .new-address-modal-btn-* replacing the Bootstrap .btn-* styles.
Updated Custom Button CSS (Replace your existing .btn styles in the modal action buttons)
instead of using btn-close, can you update the close button with the separate design?
and the close btn is not working, maybe some conflict with other code, can you provide the separate version for closing the modal?
Assistant
Certainly! Below is an updated version with a custom close button instead of the Bootstrap btn-close element, and a working independent close function to close the modal programmatically via JavaScript.
Key changes:
Custom close button markup: Using a simple styled <button> with × (multiplication sign) character.
CSS: Styled to look nice and fit top-right.
JS: Close buttons have event listener to manually close their respective modal via Bootstrap's JS API.
This approach avoids relying on data-bs-dismiss="modal" attributes that might conflict in your environment.
3. Add JavaScript to handle the close button click and close modal explicitly
Place this JS after your modals and after Bootstrap's bundle is loaded:
js
User
I got the error Uncaught TypeError: bootstrap.Modal.getInstance is not a function
when I want to close the address modal
Assistant
The error Uncaught TypeError: bootstrap.Modal.getInstance is not a function typically happens because the Bootstrap JavaScript namespace (bootstrap.Modal.getInstance) is not accessible or available in the way your code expects.
Common causes:
Bootstrap JS not fully or properly loaded
Make sure you are including the full Bootstrap 5 Bundle (bootstrap.bundle.min.js) which includes Popper and Modal.
Namespace conflict or missing import
Sometimes if you use modular imports or older Bootstrap versions, .getInstance may not exist.
Solution for your code: Access Bootstrap's Modal class directly
Modify your JS to get the Modal instance like this:
js
$(document).on('click', 'button.new-address-modal-close-btn', function () {
var modalEl = $(this).closest('.modal')[0];
if (modalEl) {
// Use bootstrap.Modal.getOrCreateInstance instead of getInstance
// This will create the modal instance if it doesn't exist yet
var modalInstance = bootstrap.Modal.getOrCreateInstance(modalEl);
modalInstance.hide();
}
});
Important notes:
.getOrCreateInstance was introduced in Bootstrap 5.1+.
If you are using Bootstrap 4 or older, .getInstance() or .getOrCreateInstance() doesn’t exist. You need to manually create:
js
var myModal = bootstrap.Modal.getInstance(modalEl);
if (!myModal) {
myModal = new bootstrap.Modal(modalEl);
}
myModal.hide();
Ensure your Bootstrap JS is v5.1 or later to use getOrCreateInstance.
How to check your Bootstrap version?
Add this in your console:
js
console.log($.fn.tooltip.Constructor.VERSION); // if jQuery plugin present
User
any other way to close the modal without using bootstrap bundle js?
Assistant
Yes, you can close a Bootstrap modal without relying on Bootstrap's JavaScript methods by directly manipulating the DOM and Bootstrap's modal classes and attributes. However, this requires you to:
Remove the .show class from the .modal element and its backdrop.
Remove the backdrop element from the DOM.
Remove the modal-open class from <body>.
Optionally trigger the modal's hidden.bs.modal event if you want to simulate Bootstrap's event system (optional).
Here is a simple plain jQuery example that closes a modal without using Bootstrap JS:
js
function closeModalWithoutBootstrapJs(modalSelector) {
const $modal = $(modalSelector);
if ($modal.length === 0) return;
// Hide modal visually
$modal.removeClass('show').attr('aria-hidden', 'true').attr('aria-modal', 'false').attr('role', 'dialog').css('display', 'none');
// Remove backdrop(s)
$('.modal-backdrop').remove();
// Remove modal-open class from body to enable scrolling again
$('body').removeClass('modal-open').css('padding-right', '');
// Optional: trigger Bootstrap hidden event (if you have listeners)
$modal.trigger('hidden.bs.modal');
}
// Close modal on your custom close button click
$(document).on('click', 'button.new-address-modal-close-btn', function () {
// Find closest modal container
const modal = $(this).closest('.modal')[0];
if(modal){
closeModalWithoutBootstrapJs(modal);
}
});
Explanation:
.removeClass('show') hides modal.
.css('display', 'none') hides modal container.
Removes the injected backdrop .modal-backdrop.
Removes modal-open class from <body>, so page scrolls again.
Triggers event so any listeners get notified (optional).
User
Please update the following script that using the latest close modal function without using Bootstrap JS:
$(function(){
let isCheckoutMode = false;
let selectedCheckoutAddressId = null;
let addressCache = {};
// Escape HTML
function escapeHtml(text) {
if(!text) return '';
return text.replace(/[&<>"']/g, function (m) {
switch (m) {
case '&': return "&";
case '<': return "<";
case '>': return ">";
case '"': return """;
case "'": return "'";
default: return m;
}
});
}
// Show alert in modal
function newAddressModalShowAlert(targetSelector, message, type = 'info') {
const html = <div class="alert alert-${type} alert-dismissible fade show" role="alert"> ${message} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div>;
$(targetSelector).html(html);
}
// Clear form and validation states
function newAddressModalClearForm() {
('#new-address-modal-form')[0].reset();
('#new-address-modal-id').val('');
('#new-address-modal-edit-alert').html('');
('#new-address-modal-form').removeClass('was-validated');
}
// Load address list from backend via AJAX
function newAddressModalLoadAddresses() {
const container = ('#new-address-modal-address-list');
const loadingText = ('#new-address-modal-loading-text');
loadingText.show();
container.children('.new-address-card').remove();
$('#new-address-modal-list-alert').html('');
code
Assistant
Sure! To close the modals without Bootstrap JS, replace all uses of bootstrap.Modal.getInstance(...).hide() with a custom function that manually hides modal DOM elements and removes backdrop and body classes.
Here’s your updated script with the close modal replaced to not use Bootstrap JS, but a custom close function:
js
User
The create/edit message should be show in the edit modal instead of address list modal, please update
Assistant
Got it! Your current code already mostly shows messages in the edit modal alert container (#new-address-modal-edit-alert) when creating/updating addresses.
The only change needed: make sure create/edit success and error messages ONLY appear in #new-address-modal-edit-alert, and no message is shown in the list modal on add/edit actions. Also, make sure that list modal alert (#new-address-modal-list-alert) is cleared after successful add/edit to avoid old messages lingering.
Below is the updated parts only you need to change in your script related to showing messages on add/edit:
1. In Ajax success/error callback inside #new-address-modal-form submit handler, use only #new-address-modal-edit-alert:
2. Make sure to clear the list modal alert when opening or after success
Add this line right after a successful add/update (before or after newAddressModalLoadAddresses()):
js
$('#new-address-modal-list-alert').html('');
Alternatively, clear it at the start of opening modal too (you might already do).
Complete revised #new-address-modal-form submit part for clarity:
js
User
When I click on "選擇為收貨地址", the error appear:
checkout:1561
Uncaught ReferenceError: addressCache is not defined
at onCheckoutAddressSelected (checkout:1561:20)
please fix it
Assistant
The error Uncaught ReferenceError: addressCache is not defined indicates that the addressCache object used inside your onCheckoutAddressSelected function is not accessible in that scope.
This often happens because:
addressCache is defined inside a closure in your modal script but is not global.
Your onCheckoutAddressSelected is either a global function outside that closure or in another script file, and it doesn't have access to the modal's internal variables.
Fix — Make addressCache globally accessible
Method 1: Define addressCache on window object
In your main modal script where you already have:
js
let addressCache = {};
Change that to:
js
window.addressCache = {};
And everywhere in your modal script that uses addressCache, replace to window.addressCache (or just addressCache if already global).
Then, in your global onCheckoutAddressSelected function:
Access the cached address via window.addressCache:
Make sure addressCache is attached to the global/window object, so any other script/function can refer to it.
In your modal AJAX load success, fill window.addressCache instead of a local variable.
Ensure your global onCheckoutAddressSelected() accesses window.addressCache.
Example update snippet inside your modal script:
User
also update the "設為預設" button hidden in checkout mode
Assistant
Certainly! To hide the "設為預設" (Set as Default) button in checkout mode, you can adjust your address rendering code to omit that button when isCheckoutMode is true.
Here’s how to update your existing code snippet inside newAddressModalLoadAddresses:
On checkout page, define the function to handle selected address from modal:
js
function onCheckoutAddressSelected(addressId) {
// You can perform AJAX request to load the address details and fill the checkout shipping form
// or update your checkout logic accordingly
$.ajax({
url: '<?= base_url("my-account/get-address-list") ?>',
type: 'GET',
data: { id: addressId, user_id: <?= $this->data['user']->id ?>, limit: 1 },
dataType: 'json',
success: function(response) {
if(response.total > 0) {
let addr = response.rows[0];
// Example: fill checkout fields
$('#checkout_name').val(addr.name);
$('#checkout_mobile').val(addr.mobile);
$('#checkout_address').val(addr.address);
// etc...
alert('收貨地址已更新,請繼續付款或結帳。');
}
}
});
}
Notes & Considerations
You might want to load the modal content dynamically if your app is very large.
Validate all user inputs properly on backend (you already have form_validation).
You can enhance UX with loading spinners, error messages etc.
Make sure you include necessary Bootstrap CSS/JS and jQuery.
Adjust field names as per your database (e.g., 'type' field for address).
The backend APIs (my-account/get-address-list, add-address, etc.) are already implemented in your controller and model.
This will enable your users to manage their addresses anywhere with modal popup, meet all your requirements including checkout-specific address choosing without affecting default addresses globally.
If you need code for Bootstrap modal triggering or AJAX loading for old Bootstrap or jQuery versions, let me know!
openNewAddressModal(false); // For address management
openNewAddressModal(true); // For checkout address selection (will add "選擇為收貨地址" buttons)
On checkout page, implement:
js
function onCheckoutAddressSelected(addressId) {
// Load address by ajax or notify your checkout form about new selected shipping address
alert('已選擇收貨地址id: ' + addressId);
// Custom handling here...
}
Summary:
Two clean modals (List + Add/Edit).
Fully AJAX driven, no page reload.
Scoped CSS and IDs/classes with prefix new-address-modal-.
Flexible mode for normal management or checkout.
Confirm dialog on delete.
Clear user feedback with Bootstrap alerts.
If you want, I can help to convert this into React/Vue or vanilla JS too. Let me know!
Remember to update your other JS code that uses this function normally!
4. Small helper function used above (escape HTML):
js
function escapeHtml(text) {
if(!text) return '';
return text.replace(/[&<>"']/g, function (m) {
switch (m) {
case '&': return "&";
case '<': return "<";
case '>': return ">";
case '"': return """;
case "'": return "'";
default: return m;
}
});
}
5. Keep other JS & modal behaviors the same from earlier demo, only replace render with this.
Summary of changes in UI:
Desktop: address blocks stacked vertically, each with:
Status badges top-right (green = default, blue = selected at checkout).
Address on top, then name, then contact no.
Buttons aligned bottom-right.
Mobile: same stacked cards, action buttons stack vertically for easy tap.
If you want, I could update entire demo with this design. But the snippet above can plug-and-play into you current codebase or my previous full demo:
Replace modal list HTML inside modal-body with the new structure container
Replace JS function rendering addresses list
Include given CSS styles
Let me know if you'd like me to send a full working example file with these updates!
Click 管理送貨地址 opens the list modal (show all dummy addresses).
Click 新增地址 opens add modal.
Edit / Delete / Set default buttons per card in the bottom-right corner.
Status badges 預設地址 and 已選擇為收貨地址 top-right.
Click 選擇收貨地址 (結帳模式) to open modal in checkout mode, and choose address button visible.
Selecting address in checkout mode shows alert and closes modal.
Feel free to test on your desktop/mobile/tablet to see responsive layout and interactions.
Any backend integration can replace dummy data and adapt ajax calls accordingly.
If you need help integrating with your backend PHP or API, just ask!
2. Implement onCheckoutAddressSelected on checkout page JS if needed:
js
function onCheckoutAddressSelected(addressId) {
alert('選擇地址ID:'+addressId);
// TODO: load that address data and update checkout shipping info
}
This solution keeps your backend functions untouched and just updates frontend UI/layout and AJAX integration with your existing endpoints.
If you want me to package the entire HTML page demo or help with PHP backend integration, please let me know!
Why AJAX?
Safer and cleaner: You get the latest fresh data.
No longer rely on hidden DOM markup.
Works well if your addresses update often.
What if you want to avoid the AJAX call?
You can store the data somewhere globally when loading into modal, e.g., keep an object like:
js
var addressCache = {}; // key = addressId, value = address data object
Fill this cache when loading addresses (newAddressModalLoadAddresses), then:
js
function onCheckoutAddressSelected(addressId) {
let addr = addressCache[addressId];
if (!addr) {
alert('地址資料不存在於快取中');
return;
}
$('#address-name').html(addr.name + (addr.type ? ' - ' + addr.type : ''));
$('#address-full').html(addr.address.replace(/\r?\n/g, '<br>'));
$('#address-mobile').html(addr.mobile);
$('#address_id').val(addr.id);
}
You'd need to modify the newAddressModalLoadAddresses to fill addressCache while rendering.
Summary
Recommended: In your onCheckoutAddressSelected callback for checkout mode, run an AJAX call to fetch full address data and fill your checkout page fields.
Alternative: Cache your addresses at modal load, then use cached data.
If you want me to help you add the caching to your modal code or if you want a full snippet using caching instead of AJAX, just ask!
Easy to customize font-size, padding, radius via .new-address-modal-btn base class.
If you want, I can provide the full integrated HTML + CSS + JS example updated with these new button styles—just ask!
$(document).ready(function(){
// Close modal on custom close button click
$(document).on('click', 'button.new-address-modal-close-btn', function() {
// Find closest .modal parent
var modalEl = $(this).closest('.modal')[0];
if(modalEl){
let modalInstance = bootstrap.Modal.getInstance(modalEl);
if(!modalInstance){
// If not initialized, create a modal instance first
modalInstance = new bootstrap.Modal(modalEl);
}
modalInstance.hide();
}
});
});
Works independently of Bootstrap's data-bs-dismiss attributes — avoids conflict with other scripts or event handlers.
Clear semantic button for accessibility (with aria-label).
Easy to style and control.
If you want, I can update the full modal HTML/CSS/JS example with these custom close buttons instead of Bootstrap’s default ones.
Let me know if you want me to prepare the full updated example!
or check the file URL or source code comments for version info.
Minimal working snippet you can use (Bootstrap5.1+):
js
$(document).on('click', 'button.new-address-modal-close-btn', function () {
var modalEl = $(this).closest('.modal')[0];
if (!modalEl) return;
var modalInstance = bootstrap.Modal.getOrCreateInstance(modalEl);
modalInstance.hide();
});
If .getOrCreateInstance is undefined, fallback:
js
$(document).on('click', 'button.new-address-modal-close-btn', function () {
var modalEl = $(this).closest('.modal')[0];
if (!modalEl) return;
var modalInstance;
if (typeof bootstrap.Modal.getOrCreateInstance === 'function') {
modalInstance = bootstrap.Modal.getOrCreateInstance(modalEl);
} else if (typeof bootstrap.Modal.getInstance === 'function') {
modalInstance = bootstrap.Modal.getInstance(modalEl);
if (!modalInstance) {
modalInstance = new bootstrap.Modal(modalEl);
}
} else {
modalInstance = new bootstrap.Modal(modalEl);
}
modalInstance.hide();
});
Summary:
Use .getOrCreateInstance for Bootstrap 5.1+
Use fallback approaches for older versions
Ensure you load Bootstrap Bundle JS (bootstrap.bundle.min.js), not just bootstrap.min.js
If you want, I can also provide a complete minimal example with this fix included. Just let me know!
hidden.bs.modal
Important notes:
This works if you only manually open the modal by adding .show class and .modal-backdrop elements.
If your modal was opened manually or you don’t have Bootstrap’s JS at all, this is a safe fallback.
You have to make sure modal open process adds .show and .modal-backdrop accordingly (or you manage that manually yourself).
If you are using some Bootstrap modal features relying on JS, this might break them (e.g. focus trap).
If you want to open modal manually without Bootstrap JS, you also need to implement adding .show, backdrop, and modal-open class to <body>, for example:
js
function openModalWithoutBootstrapJs(modalSelector) {
const $modal = $(modalSelector);
if ($modal.length === 0) return;
// Show modal visually
$modal.css('display', 'block').addClass('show').attr('aria-hidden', 'false').attr('aria-modal', 'true').attr('role', 'dialog');
// Append backdrop
$('<div class="modal-backdrop fade show"></div>').appendTo('body');
// Prevent background scroll
$('body').addClass('modal-open').css('padding-right', ''); // you can calculate padding-right if needed for scrollbar compensation
}
Summary
You can totally handle modal open/close purely by toggling classes/styles and managing your own backdrop.
This approach ensures no dependency on Bootstrap JS, but you lose some accessibility and focus handling provided by Bootstrap.
If you want, I can help you write a small lightweight vanilla JS/jQuery modal manager for your address modal to open/close without Bootstrap JS — just ask!
// Example: open modal for manage or checkout
// Call from anywhere:
// openNewAddressModal(false); // management mode
// openNewAddressModal(true); // checkout mode with choose button
});
$(function(){
let isCheckoutMode = false;
let selectedCheckoutAddressId = null;
let addressCache = {};
// Escape HTML
function escapeHtml(text) {
if(!text) return '';
return text.replace(/[&<>"']/g, function (m) {
switch (m) {
case '&': return "&";
case '<': return "<";
case '>': return ">";
case '"': return """;
case "'": return "'";
default: return m;
}
});
}
// Show alert in modal
function newAddressModalShowAlert(targetSelector, message, type = 'info') {
const html = `
<div class="alert alert-${type} alert-dismissible fade show" role="alert">
${message}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>`;
$(targetSelector).html(html);
}
// Clear form and validation states
function newAddressModalClearForm() {
$('#new-address-modal-form')[0].reset();
$('#new-address-modal-id').val('');
$('#new-address-modal-edit-alert').html('');
$('#new-address-modal-form').removeClass('was-validated');
}
// Custom close modal function WITHOUT Bootstrap JS dependency
function closeModalWithoutBootstrapJs(modalSelector) {
const $modal = $(modalSelector);
if ($modal.length === 0) return;
// Hide modal container
$modal.removeClass('show').attr('aria-hidden', 'true').attr('aria-modal', 'false').attr('role', 'dialog').css('display', 'none');
// Remove backdrop(s)
$('.modal-backdrop').remove();
// Remove body modal-open class and inline padding-right style
$('body').removeClass('modal-open').css('padding-right', '');
// Optional: trigger hidden event if you listen to it
$modal.trigger('hidden.bs.modal');
}
// Load address list from backend via AJAX
function newAddressModalLoadAddresses() {
const container = $('#new-address-modal-address-list');
const loadingText = $('#new-address-modal-loading-text');
loadingText.show();
container.children('.new-address-card').remove();
$('#new-address-modal-list-alert').html('');
$.ajax({
url: '<?= base_url('my-account/get-address-list') ?>',
type: 'GET',
data: { user_id: <?= $this->data['user']->id ?>, limit: 1000 },
dataType: 'json',
success: function(res){
loadingText.hide();
addressCache = {};
if(!res.total || res.total === 0) {
container.html('<div class="text-center text-muted py-4">尚無地址資料</div>');
return;
}
let html = '';
res.rows.forEach(addr => {
addressCache[addr.id] = addr;
let statusHtml = '';
if(addr.is_default == 1 || addr.action.includes('預設地址')) statusHtml += `<span class="default-badge">預設地址</span>`;
if(isCheckoutMode && selectedCheckoutAddressId == addr.id) {
statusHtml += `<span class="selected-badge">已選擇為收貨地址</span>`;
}
html += `
<div class="new-address-card" data-id="${addr.id}" style="position: relative;">
<div class="new-address-card-status">${statusHtml}</div>
<div class="new-address-card-details">
<div class="new-address-card-field"><span class="label">地址:</span> ${escapeHtml(addr.address).replace(/\r?\n/g, '<br/>')}</div>
<div class="new-address-card-field"><span class="label">姓名:</span> ${escapeHtml(addr.name)}</div>
<div class="new-address-card-field"><span class="label">聯絡電話:</span> ${escapeHtml(addr.mobile)}${addr.alternate_mobile ? ' / ' + escapeHtml(addr.alternate_mobile) : ''}</div>
</div>
<div class="new-address-card-actions">
<button type="button" class="new-address-modal-btn new-address-modal-btn-outline-primary new-address-modal-edit-btn" data-id="${addr.id}">編輯</button>
<button type="button" class="new-address-modal-btn new-address-modal-btn-outline-danger new-address-modal-delete-btn" data-id="${addr.id}">刪除</button>
${isCheckoutMode ? `<button type="button" class="new-address-modal-btn new-address-modal-btn-outline-info new-address-modal-choose-btn" data-id="${addr.id}">選擇為收貨地址</button>` : ''}
${addr.is_default == 1 ? '' : `<button type="button" class="new-address-modal-btn new-address-modal-btn-outline-secondary new-address-modal-set-default-btn" data-id="${addr.id}">設為預設</button>`}
</div>
</div>
`;
});
container.html(html);
},
error: function(){
loadingText.hide();
container.html('<div class="text-center text-danger py-4">無法載入地址資料</div>');
}
});
}
// Fill the add/edit form by ID
function newAddressModalFillForm(id) {
$('#new-address-modal-edit-alert').html('');
$.ajax({
url: '<?= base_url('my-account/get-address-list') ?>',
type: 'GET',
data: { user_id: <?= $this->data['user']->id ?>, limit: 1, id: id },
dataType: 'json',
success: function(res) {
if(res.total && res.rows.length > 0) {
const addr = res.rows[0];
$('#new-address-modal-id').val(addr.id);
$('#new-address-modal-name').val(addr.name);
$('#new-address-modal-mobile').val(addr.mobile);
$('#new-address-modal-alternate-mobile').val(addr.alternate_mobile);
$('#new-address-modal-address').val(addr.address.replace(/<br\s*\/?>/gi,"\n"));
$('#new-address-modal-type').val(addr.type);
$('#new-address-modal-edit-label').text('編輯地址');
$('#new-address-modal-form').removeClass('was-validated');
// Open modal manually without Bootstrap JS modal API
$('#new-address-modal-edit').css({display:'block'}).addClass('show').attr({'aria-hidden':'false','aria-modal':'true','role':'dialog'});
$('body').addClass('modal-open');
// Add backdrop manually if needed
if($('.modal-backdrop').length === 0){
$('<div class="modal-backdrop fade show"></div>').appendTo('body');
}
} else {
newAddressModalShowAlert('#new-address-modal-list-alert', '查無此地址', 'danger');
}
},
error: function() {
newAddressModalShowAlert('#new-address-modal-list-alert', '無法取得地址資料', 'danger');
}
});
}
// Open the list modal (manually without Bootstrap modal API)
window.openNewAddressModal = function(checkoutMode=false) {
isCheckoutMode = checkoutMode;
selectedCheckoutAddressId = null;
$('#new-address-modal-list-label').text(isCheckoutMode ? '選擇收貨地址' : '管理送貨地址');
$('#new-address-modal-list-alert').html('');
newAddressModalClearForm();
newAddressModalLoadAddresses();
$('#new-address-modal-list').css({display:'block'}).addClass('show').attr({'aria-hidden':'false','aria-modal':'true','role':'dialog'});
$('body').addClass('modal-open');
if($('.modal-backdrop').length === 0){
$('<div class="modal-backdrop fade show"></div>').appendTo('body');
}
};
// Event binding
// Custom close buttons - manually close modal without bootstrap JS
$(document).on('click', 'button.new-address-modal-close-btn', function() {
var modal = $(this).closest('.modal');
closeModalWithoutBootstrapJs(modal);
});
$(document).on('click', '#new-address-modal-add-new-btn', function(){
newAddressModalClearForm();
$('#new-address-modal-edit-label').text('新增地址');
// open add/edit modal manually
$('#new-address-modal-edit').css({display:'block'}).addClass('show').attr({'aria-hidden':'false','aria-modal':'true','role':'dialog'});
$('body').addClass('modal-open');
if($('.modal-backdrop').length === 0){
$('<div class="modal-backdrop fade show"></div>').appendTo('body');
}
});
$(document).on('click', '.new-address-modal-edit-btn', function(){
let id = $(this).data('id');
newAddressModalFillForm(id);
});
$(document).on('click', '.new-address-modal-delete-btn', function(){
let id = $(this).data('id');
if(confirm('確定要刪除此地址嗎?')) {
$.ajax({
url: '<?= base_url('my-account/delete_address') ?>',
type: 'POST',
data: { id: id },
dataType: 'json',
success: function(res) {
if(!res.error) {
newAddressModalShowAlert('#new-address-modal-list-alert', '刪除成功', 'success');
newAddressModalLoadAddresses();
} else {
newAddressModalShowAlert('#new-address-modal-list-alert', res.message || '刪除失敗', 'danger');
}
},
error: function() {
newAddressModalShowAlert('#new-address-modal-list-alert', '刪除失敗,請稍後再試', 'danger');
}
});
}
});
$(document).on('click', '.new-address-modal-set-default-btn', function(){
let id = $(this).data('id');
$.ajax({
url: '<?= base_url('my-account/set_default_address') ?>',
method: 'POST',
data: { id: id },
dataType: 'json',
success: function(res) {
if(!res.error) {
newAddressModalShowAlert('#new-address-modal-list-alert', '已設為預設地址', 'success');
newAddressModalLoadAddresses();
} else {
newAddressModalShowAlert('#new-address-modal-list-alert', res.message || '設定失敗', 'danger');
}
},
error: function() {
newAddressModalShowAlert('#new-address-modal-list-alert', '設定失敗,請稍後再試', 'danger');
}
});
});
$(document).on('click', '.new-address-modal-choose-btn', function(){
if(!isCheckoutMode) return;
let id = $(this).data('id');
selectedCheckoutAddressId = id;
if(typeof window.onCheckoutAddressSelected === 'function') {
window.onCheckoutAddressSelected(id);
}
closeModalWithoutBootstrapJs('#new-address-modal-list');
});
// Submit add/edit form
$('#new-address-modal-form').on('submit', function(e){
e.preventDefault();
const form = this;
form.classList.add('was-validated');
if(!form.checkValidity()){
return;
}
const id = $('#new-address-modal-id').val();
const postUrl = id ? '<?= base_url('my-account/edit_address') ?>' : '<?= base_url('my-account/add-address') ?>';
const formData = $(this).serialize();
$('#new-address-modal-save-btn').prop('disabled', true).text('處理中...');
$.ajax({
url: postUrl,
type: 'POST',
data: formData,
dataType: 'json',
success: function(res){
if(!res.error){
newAddressModalShowAlert('#new-address-modal-edit-alert', res.message, 'success');
newAddressModalClearForm();
newAddressModalLoadAddresses();
setTimeout(() =>{
closeModalWithoutBootstrapJs('#new-address-modal-edit');
}, 1000);
} else {
newAddressModalShowAlert('#new-address-modal-edit-alert', res.message || '儲存失敗', 'danger');
}
},
error: function(){
newAddressModalShowAlert('#new-address-modal-edit-alert', '伺服器錯誤,請稍後再試', 'danger');
},
complete: function(){
$('#new-address-modal-save-btn').prop('disabled', false).text('儲存');
}
});
});
// -- End of document ready --
});
Explanation:
When opening modals, you manually add .show class, set display: block, set ARIA attrs, add backdrop div .modal-backdrop, and add modal-open to <body>.
When closing modals (via close buttons or after successful ajax), call closeModalWithoutBootstrapJs(selector) that removes .show, hides the modal, removes backdrop and body scroll lock.
No Bootstrap modal JS methods used.
Backdrop created manually if not present.
This is a lightweight way to control modals without Bootstrap's JS dependency.
If you want, I can help add example CSS for backdrop and modal show styles to ensure smooth animation and proper appearance with this approach!
$('#new-address-modal-form').on('submit', function(e){
e.preventDefault();
const form = this;
form.classList.add('was-validated');
if(!form.checkValidity()){
return;
}
const id = $('#new-address-modal-id').val();
const postUrl = id ? '<?= base_url('my-account/edit_address') ?>' : '<?= base_url('my-account/add-address') ?>';
const formData = $(this).serialize();
$('#new-address-modal-save-btn').prop('disabled', true).text('處理中...');
$.ajax({
url: postUrl,
type: 'POST',
data: formData,
dataType: 'json',
success: function(res){
if(!res.error){
// Show message only in edit modal alert
newAddressModalShowAlert('#new-address-modal-edit-alert', res.message, 'success');
newAddressModalClearForm();
// Clear any alert in list modal
$('#new-address-modal-list-alert').html('');
// Reload address list
newAddressModalLoadAddresses();
setTimeout(() =>{
closeModalWithoutBootstrapJs('#new-address-modal-edit');
}, 1000);
} else {
newAddressModalShowAlert('#new-address-modal-edit-alert', res.message || '儲存失敗', 'danger');
}
},
error: function(){
newAddressModalShowAlert('#new-address-modal-edit-alert', '伺服器錯誤,請稍後再試', 'danger');
},
complete: function(){
$('#new-address-modal-save-btn').prop('disabled', false).text('儲存');
}
});
});
This keeps your user experience clean:
Add/Edit results appear inside the edit modal only
No leftover messages in the list modal
The list modal alerts are used only for list related messages (delete, load errors etc)
If you want me to provide a full updated script snippet or full file with this incorporated, just let me know!