OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

how can load the dynamic form after one click again in JQUERY?

  • Thread starter Thread starter Maryam12 forex
  • Start date Start date
M

Maryam12 forex

Guest
this is my script to load a partial form for adding new address:

Code:
 function handleLocationChange() {
     var selectedLocationId = $(this).val();
     var subLocationSelect = $(this).closest("form").find("#SubLocation_Id");
     subLocationSelect.empty();

     // That was fist script for showing for 1 page ( not Dynamic form)
     $.ajax({
         url: "/UserPanel/Home/GetDistrictGroup/" + selectedLocationId,
         type: "GET",
         dataType: "json", // Specify JSON dataType
         success: function (data) {
             $.map(data, function (item) {
                 subLocationSelect.append('<option value=' + item.locationId + '>' + item.stateName + '</option>');
             });
         },
         error: function () {
             alert('Error occurred while loading districts.');
         }
     });
 }



 //** For Show click on AddNewAddress for First Form & reload partial Form again

 $(document).ready(function () {

     // Handle initial and dynamic forms change event in Location_Id  of form
     //.on is an order: change event on dynamic element: Here is Location_Id  in handleLocationChange:

     $("#addNewAddressContainer").on("change", "#Location_Id", handleLocationChange);   // First was " $("#btnAddNewAddress").click(function () " But change for changing and LocationId

     // Click event for adding new address
     $("#btnAddNewAddress").click(function () {
         var url = $(this).data("url");
         $.ajax({
             url: url,
             type: 'GET',
             success: function (data) {
                 $("#addNewAddressContainer").empty().append(data);
                 // Bind change event for Location_Id in dynamically loaded form
                 $("#addNewAddressContainer").find("form:last #Location_Id").change(handleLocationChange);
             },

             error: function () {
                 alert('Error occurred while loading the form.');
             }
         });
     });

after load the form I have some operation like add new address in data base and return to page and update view with ajax.
but after finishing the submit ion , the button does not work again, it means if I click on it it does not work . how can I handle it work in all status , before click and submission and after it ?

Code:
     // Handle form submission AddNewAddress Form

     $("#addNewAddressContainer").on("submit", "form", function (e) {
         e.preventDefault();

         var $form = $(this);
         var formData = $form.serialize();

         $.ajax({
             url: $form.attr("action"),
             type: $form.attr("method"),
             data: formData,
             success: function (response) {
                 if (response.success) {
                     ShowMessage(response.message); // From My ShowMessage Method
                     $form.hide();

                     $('html, body').animate({ scrollTop: 0 }, 'fast');

                     // بعد از اضافه شدن آدرس جدید، لیست آدرس‌ها را به‌روزرسانی کنید
                     fetchAndUpdateAddressList();
                 } else {
                     ShowMessage(response.message);
                 }
             },
             error: function () {
                 ShowMessage('Error occurred while submitting the form.');
             }
         });
     });


     function fetchAndUpdateAddressList() {
         $.ajax({
             url: '/UserPanel/Home/GetClientContactInfoById', // تغییر دهید به کنترلر و اکشن مناسب
             type: 'GET',
             success: function (addresses) {
                 console.log(addresses); // بررسی کنید که آیا داده‌ها به درستی دریافت می‌شوند
                 var $addressListContainer = $("#addressListContainer"); // Select the container where addresses are displayed
                 $addressListContainer.empty(); // Clear the current list



                 // Check if there are addresses
                 if (addresses.length > 0) {
                     addresses.forEach(function (address) {
                         // Check for undefined values and set default values if needed
                         var addressValue = address.address || '';
                         var stateValue = address.state || '';
                         var districtValue = address.district || '';
                         var zipCodeValue = address.zipCode || '';
                         var locationIdValue = address.locationId || '';

                         var addressHtml = `
                                 <div class="row mb-3">
                                     <div class="col-lg-12">
                                         <div class="input-group mb-3">
                                             <div class="input-group-prepend">
                                                 <div class="input-group-text">
                                                     <input type="radio" name="CartAddresses" value="${locationIdValue}" checked>
                                                 </div>
                                             </div>
                                             <input type="text" name="address" class="form-control" placeholder="Address" value="${addressValue}" readonly="readonly">
                                         </div>
                                     </div>
                                     <div class="col-md-5 mb-3">
                                         <div class="control-group">
                                             <label>State</label>
                                             <div class="input-group">
                                                 <select class="form-control" disabled>
                                                     <option disabled selected>${stateValue}</option>
                                                 </select>
                                                 <div class="input-group-append">
                                                     <div class="input-group-text"><i class="fa fa-chevron-down"></i></div>
                                                 </div>
                                             </div>
                                         </div>
                                     </div>
                                     <div class="col-md-5 mb-3">
                                         <div class="control-group">
                                             <label>District</label>
                                             <div class="input-group">
                                                 <select class="form-control" disabled>
                                                     <option disabled selected>${districtValue}</option>
                                                 </select>
                                                 <div class="input-group-append">
                                                     <div class="input-group-text"><i class="fa fa-chevron-down"></i></div>
                                                 </div>
                                             </div>
                                         </div>
                                     </div>
                                     <div class="col-md-2 mb-3">
                                         <div class="control-group">
                                             <label>Zip Code</label>
                                             <input type="number" class="form-control" value="${zipCodeValue}" readonly="readonly">
                                             <span></span>
                                         </div>
                                     </div>
                                 </div>
                                 <hr/>
                             `;
                         $addressListContainer.append(addressHtml);
                     });
                 }

                 // Add the button to add new addresses
                 var addNewAddressHtml = `
                         <div class="row">
                             <div class="col-lg-12">
                                 <span class="font-weight-bold">
                                     <button id="btnAddNewAddress" type="button" class="btn btn-primary" data-url="/YourController/GetAddNewAddressForm">
                                         <i class="fa fa-plus" aria-hidden="true"></i> Add New Address
                                     </button>
                                 </span>
                             </div>
                         </div>
                         <div id="addNewAddressContainer"></div>
                     `;
                 $addressListContainer.append(addNewAddressHtml);
             },
             error: function () {
                 ShowMessage('Error occurred while fetching addresses.');
             }
         });
     }

<p>this is my script to load a partial form for adding new address:</p>
<pre><code> function handleLocationChange() {
var selectedLocationId = $(this).val();
var subLocationSelect = $(this).closest("form").find("#SubLocation_Id");
subLocationSelect.empty();

// That was fist script for showing for 1 page ( not Dynamic form)
$.ajax({
url: "/UserPanel/Home/GetDistrictGroup/" + selectedLocationId,
type: "GET",
dataType: "json", // Specify JSON dataType
success: function (data) {
$.map(data, function (item) {
subLocationSelect.append('<option value=' + item.locationId + '>' + item.stateName + '</option>');
});
},
error: function () {
alert('Error occurred while loading districts.');
}
});
}



//** For Show click on AddNewAddress for First Form & reload partial Form again

$(document).ready(function () {

// Handle initial and dynamic forms change event in Location_Id of form
//.on is an order: change event on dynamic element: Here is Location_Id in handleLocationChange:

$("#addNewAddressContainer").on("change", "#Location_Id", handleLocationChange); // First was " $("#btnAddNewAddress").click(function () " But change for changing and LocationId

// Click event for adding new address
$("#btnAddNewAddress").click(function () {
var url = $(this).data("url");
$.ajax({
url: url,
type: 'GET',
success: function (data) {
$("#addNewAddressContainer").empty().append(data);
// Bind change event for Location_Id in dynamically loaded form
$("#addNewAddressContainer").find("form:last #Location_Id").change(handleLocationChange);
},

error: function () {
alert('Error occurred while loading the form.');
}
});
});
</code></pre>
<p>after load the form I have some operation like add new address in data base and return to page and update view with ajax.<br />
but after finishing the submit ion , the button does not work again, it means if I click on it it does not work . how can I handle it work in all status , before click and submission and after it ?</p>
<pre><code> // Handle form submission AddNewAddress Form

$("#addNewAddressContainer").on("submit", "form", function (e) {
e.preventDefault();

var $form = $(this);
var formData = $form.serialize();

$.ajax({
url: $form.attr("action"),
type: $form.attr("method"),
data: formData,
success: function (response) {
if (response.success) {
ShowMessage(response.message); // From My ShowMessage Method
$form.hide();

$('html, body').animate({ scrollTop: 0 }, 'fast');

// بعد از اضافه شدن آدرس جدید، لیست آدرس‌ها را به‌روزرسانی کنید
fetchAndUpdateAddressList();
} else {
ShowMessage(response.message);
}
},
error: function () {
ShowMessage('Error occurred while submitting the form.');
}
});
});


function fetchAndUpdateAddressList() {
$.ajax({
url: '/UserPanel/Home/GetClientContactInfoById', // تغییر دهید به کنترلر و اکشن مناسب
type: 'GET',
success: function (addresses) {
console.log(addresses); // بررسی کنید که آیا داده‌ها به درستی دریافت می‌شوند
var $addressListContainer = $("#addressListContainer"); // Select the container where addresses are displayed
$addressListContainer.empty(); // Clear the current list



// Check if there are addresses
if (addresses.length > 0) {
addresses.forEach(function (address) {
// Check for undefined values and set default values if needed
var addressValue = address.address || '';
var stateValue = address.state || '';
var districtValue = address.district || '';
var zipCodeValue = address.zipCode || '';
var locationIdValue = address.locationId || '';

var addressHtml = `
<div class="row mb-3">
<div class="col-lg-12">
<div class="input-group mb-3">
<div class="input-group-prepend">
<div class="input-group-text">
<input type="radio" name="CartAddresses" value="${locationIdValue}" checked>
</div>
</div>
<input type="text" name="address" class="form-control" placeholder="Address" value="${addressValue}" readonly="readonly">
</div>
</div>
<div class="col-md-5 mb-3">
<div class="control-group">
<label>State</label>
<div class="input-group">
<select class="form-control" disabled>
<option disabled selected>${stateValue}</option>
</select>
<div class="input-group-append">
<div class="input-group-text"><i class="fa fa-chevron-down"></i></div>
</div>
</div>
</div>
</div>
<div class="col-md-5 mb-3">
<div class="control-group">
<label>District</label>
<div class="input-group">
<select class="form-control" disabled>
<option disabled selected>${districtValue}</option>
</select>
<div class="input-group-append">
<div class="input-group-text"><i class="fa fa-chevron-down"></i></div>
</div>
</div>
</div>
</div>
<div class="col-md-2 mb-3">
<div class="control-group">
<label>Zip Code</label>
<input type="number" class="form-control" value="${zipCodeValue}" readonly="readonly">
<span></span>
</div>
</div>
</div>
<hr/>
`;
$addressListContainer.append(addressHtml);
});
}

// Add the button to add new addresses
var addNewAddressHtml = `
<div class="row">
<div class="col-lg-12">
<span class="font-weight-bold">
<button id="btnAddNewAddress" type="button" class="btn btn-primary" data-url="/YourController/GetAddNewAddressForm">
<i class="fa fa-plus" aria-hidden="true"></i> Add New Address
</button>
</span>
</div>
</div>
<div id="addNewAddressContainer"></div>
`;
$addressListContainer.append(addNewAddressHtml);
},
error: function () {
ShowMessage('Error occurred while fetching addresses.');
}
});
}
</code></pre>
 

Latest posts

Top