JQuery unable to post dynamically added form elements - javascript

I have read the previous posts on this, but I can't seem to resolve my issue. I have a form that has static and dynamically created input fields. The static fields are being posted without issue. However, none of the dynamically created :inputs are coming across in the post request.
The form :
<div id="userModal" class="modal fade" style="display:none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="btn btn-primary" style="float:right;margin-bottom:4px;">Delete User
</button>
<h4 class="modal-title">Edit User : <span id="user_webUserProfilePrimaryName"></span></h4>
</div>
<div class="modal-body">
<span id="user_maintain_messages" name="user_maintain_messages"></span>
<form id="editUserForm" name="editUserForm">
<input type="hidden" name="user_maintain_action" id="user_maintain_action" value="update">
<input type="hidden" name="action" id="action" value="sc_admin_updateCustomerFundInfo">
<input type="hidden" name="version" id="version" value="1.1" ;
<div class="row">
<div class="form-group">
<div class="col-md-4">
<label for="user_webUserLevel">User Level</label>
</div>
<div class="col-md-6">
<select class="form-control" id="user_webUserLevel" name="user_webUserLevel">
<option value="anonymous">Pending</option>
<option value="customer">Customer</option>
<option value="administrator">Admin</option>
<option value="superuser">Super</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-4">
<label for="user_webUserProfileStatus">User Status</label>
</div>
<div class="col-md-6">
<select class="form-control" name="user_webUserProfileStatus"
name="user_webUserProfileStatus">
<option value="InReview">In Review</option>
<option value="Approved">Approved</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-4">
<label for="user_verified">User Verified</label>
</div>
<div class="col-md-6">
<select class="form-control" id="user_verified" name="user_verified">
<option value="N">Not Verified</option>
<option value="Y">Verified</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-4">
<label for="webUserName">Send Login Confirmation</label>
</div>
<div class="col-md-6">
<span id="user_sendConfirmButton"></span>
</div>
</div>
</div>
<div class="row">
<table class="table" id="user_fundTable">
<thead>
<tr>
<th>Fund(s)</th>
<th>Account #</th>
<th>Administrator</th>
<th>Status</th>
</tr>
</thead>
<tfoot>
</tfoot>
<tbody>
</tbody>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" style="background:grey;float:left" data-dismiss="modal">
Cancel
</button>
<button type="button" class="btn btn-primary" onclick="saveUserMaintain()">Update (confirm changes)
</button>
</div>
</div>
</div>
</div>
It is populated with the following data :
{"Result":"OK","Records":[{"webUserProfilePrimaryName":"Johnny Appleseed","verified":"N","webUserProfileId":"24","webUserLevel":"anonymous","webUserProfileStatus":"InReview","webUserProfileReferenceAccount":"19, 30, 3126, 0090","fund":[{"fundName":"PCF","fundFullName":"Private Capital Fund","fundAccess":"RO","fundAccNo":0,"latestStatement":"","fundManager":"","status":"Approved"},{"fundName":"CCIF","fundFullName":"Coast Capital Income Fund","fundAccess":"RO","fundAccNo":0,"latestStatement":"","fundManager":"","status":"Approved"},{"fundName":"SIF2","fundFullName":"Secured Income Fund","fundAccess":"RO","fundAccNo":0,"latestStatement":"","fundManager":"","status":"Approved"}],"sendConfirm":"<button class='btn btn-primary' onclick='sendConfirmEmail(\"24\")'>Email Now<\/button>"}]}
I use this function to populate my form :
function showUserMaintain(webUserProfileId) {
jQuery.post(stonecrestajax.ajaxurl, {
action: "sc_admin_getCustomerFundInfo",
webUserProfileId: webUserProfileId,
version: "1.1"
}, function (data) {
console.log(data['Records'][0]['webUserProfilePrimaryName']);
jQuery("#user_webUserProfilePrimaryName").html(data['Records'][0]['webUserProfilePrimaryName']);
jQuery("#user_webUserLevel").val(data['Records'][0]['webUserLevel']);
jQuery("#user_webUserProfileStatus").val(data['Records'][0]['webUserProfileStatus']);
jQuery("#user_verified").val(data['Records'][0]['verified']);
jQuery("#user_sendConfirmButton").html(data['Records'][0]['sendConfirm']);
jQuery('#user_fundTable tbody').empty();
jQuery.each(data['Records'][0]['fund'], function (fundIdx, fundValues) {
var fundStatusOptions = ["In Review", "New", "Approved"];
var combo = generateDropDownList(fundIdx, fundIdx, fundStatusOptions);
var row = '<tr><td>' + fundValues.fundName + '</td>';
row += '<td><input type="text" name="user_fundAccountNumber[]" id="user_fundAccountNumber_' + fundIdx + '" value="' + fundValues.fundAccNo + '"></td>';
row += '<td><input type="text" name="user_fundManagerName[]" id="user_fundManagerName_' + fundIdx + '" value="' + fundValues.fundManager + '"></td>';
row += '<td id="user_fundStatus_' + fundIdx + '" name="user_fundStatus_' + fundIdx + '"></td></tr>';
jQuery('#user_fundTable').append(row);
//jQuery("#user_fundStatus_" + fundIdx).append(combo);
//console.log(fundValues);
});
jQuery("#userModal").modal('show');
}, "json");
}
As you can see from the function I'm dynamically adding values to existing input fields and dynamically creating some input fields within a table that is within the form.
However, when I try to serialize (post) the form back to the server using this
function :
function saveUserMaintain() {
jQuery.ajax({
type: "POST",
url: url,
data: jQuery("#editUserForm").serialize(),
success: function (data) {
alert(data);
}
});
return false;
}
The only data I see coming across are the fields (inputs) I had statically defined, none of the "user_fundXXXXXX" fields are coming across in the post request.
I'm sure I'm just standing too far inside the box and can't see the obvious here, can anyone give me a hand ?

Related

Javascript function works only on the first table row inside my foreach laravel loop

I am using a javascript functions to input a number and automatically display the result after calculation inside a boostrap modal.
If click the request button at the first row, javascript functions work well. But when I click on the request button on the second row and succeeding rows, it doesn't function.
I am not really sure if the problem is the data inside the modal or the data outside the modal
I tried to getElementsByClassName instead of ID but it still not working.
<script>
function mult(value) { // === calculate the profit and the total amount due === //
var x = value * 15 / 100;
var y = parseFloat(x)+parseInt(value);
document.getElementById("profit").value = x;
document.getElementById("total").value = y;
}
</script>
<table id="table1">
<thead>
<tr>
<th>#</th>
<th>Full Name</th>
<th>Requests</th>
</tr>
</thead>
<tbody>
#foreach($Clients as $Client)
<tr id="foreach-row">
<td>{{ $Client->full_name }}</td>
<td>
<div class="buttons">
<a class="btn icon btn-secondary" data-toggle="modal"
data-target="#LoanRequestModel-{{ $Client->id }}">
Request
</a>
</div>
</td>
</tr>
{{-- =========== MODEL - NEW REQUEST ===============--}}
<div class="modal" id="LoanRequestModel-{{ $Client->id }}" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><b>REQUEST</b></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<form action="{{ route('finance.storeRequest', $Client->id) }}" method="post"
class="loanrequest_form" enctype="multipart/form-data">
{{ csrf_field() }}
<label>Full name</label>
<div class="form-group">
<input type="text" name="creditor_full_name"
class="form-control" value="{{ $Client->full_name }}" >
</div>
<div>
<label>Amount</label>
<div class="form-group">
<input type="number" name="loan_amount"
class="form-control" onkeyup="mult(this.value);" >
</div>
</div>
<div class="row">
<div class="col-md-5">
<label>Interest Rate</label>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Choose</label>
<select class="form-select rate"name="interest_rate" >
<option value="15" selected>15%</option>
<option value="20">20%</option>
</select>
</div>
</div>
<div class="col-md-7">
<label>Profit</label>
<div class="input-group mb-3">
<input type="text" id="profit" class="form-control" name="profit"
aria-label="Amount">
</div>
</div>
</div>
<div class="row">
<label>Total Amount due</label>
<div class="input-group mb-3">
<input type="text" id="total" class="form-control" name="amount_due"
aria-label="Amount">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-outline-secondary ml-1" >
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">Submit</span>
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#endforeach
</tbody>
</table>
The problem - as others have said above - is that whilst you are making the ID of each modal unique using :
id="LoanRequestModel-{{ $Client->id }}"
within your loop, when generating each modal, you are using fields which have non-unique IDs :
type="text" id="profit"
type="text" id="total"
What you would be better off is making those IDs non-unique, in the same way that you did with the modal ID :
type="text" id="profit-{{ $Client->id }}"
type="text" id="total-{{ $Client->id }}"
and add IDs to the fields which you will need to use in your script that does not presently have one :
type="number" id="loan_amount-{{ $Client->id}}" name="loan_amount"
Then, when you trigger the javascript on keyup here :
onkeyup="mult(this.value);"
rather than pass the value of the field, pass the client ID :
onkeyup="mult({{ $Client->id);"
Then you just need to adjust your javascript (because it's no longer being passed the loan_amount) so that it first gets the loan_amount, then the other bits and pieces it needs, and finally returns them to the right place :
<script>
function mult(id) { // === this is now receiving the ID, not a value so first we need to get the value for the relevant field *emphasized text*== //
var value = document.getElementById("loan_amount-" + id).value
var x = value * 15 / 100;
var y = parseFloat(x)+parseInt(value);
document.getElementById("profit" + id).value = x;
document.getElementById("total" + id).value = y;
}
</script>

How to select laravel option in edit ajax

I have my data returning to table by ajax and in that data I also have edit form.
In my edit form I have select options which the data is dynamic and returning perfectly but I am not able to add selected attribute to saved option in database (it always shows first one)
Screenshot
As you can see in this screenshot my edit form cannot get correct option in selects.
NOTE:
If my data was returning by blade loop #foreach() I would select my correct option with something like this:
{{ $location->province_id == $province->id ? 'selected' : '' }}
<option value="{{$province->id}}" {{ $location->province_id == $province->id ? 'selected' : '' }}>{{$province->name}}</option>
but since my loop is in ajax code I cannot use that method.
Code
HTML
<table id="dataTableLocations" class="table table-striped table-bordered">
<thead>
<tr>
<th width="30">Seq No.</th>
<th>Name</th>
<th>Customer</th>
<th>Province</th>
<th>City</th>
<th>Address</th>
<th>Postal Code</th>
<th width="120">Options</th>
</tr>
</thead>
<tbody id="table_dataLocations"></tbody>
</table>
Script
I have commented my select options in code so you can find them faster
//ajax call (rest of the code
success:function(data){
// return existed data to locations
$('#table_dataLocations').html('');
$(data.locations).each(function(_, i){
var url = '{{ route("customer-locations.destroy", ":id") }}';
url = url.replace(':id', i.id);
var row = `<tr data-id="${i.id}">'+
'<td>${i.seqNo}</td>'+
'<td>${i.name}</td>'+
'<td>${i.customer.name}</td>'+
'<td>${i.province.name}</td>'+
'<td>${i.city.name}</td>'+
'<td>${i.address}</td>'+
'<td>${i.postalCode}</td>'+
'<td width="120">
<button type="button" class="btn btn-sm btn-info" data-toggle="modal" data-target="#editModal-${i.id}">
Edit
</button>
<!-- edit -->
<div class="modal fade effect-flip-horizontal editModalLocation" id="editModal-${i.id}" tabindex="-1" role="dialog" aria-labelledby="editModal-${i.id}Label">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="editModal-${i.id}Label">Edit ${i.name}</h4>
</div>
<form id="updateLocation" method="post" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="modal-body">
<div class="row" style="margin-bottom:7px;">
<div class="col-md-6">
<div class="form-group" style="width:100%">
<div class="sm-form-design">
<textarea style="width:100%" name="addressLocationUpdate" id="addressLocationUpdate" cols="30" rows="10" class="form-control" placeholder="Please enter your customer address." >${i.address}</textarea>
<label class="control-label">Address</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="row">
<div class="col-md-12 sm-form-design" style="margin-bottom:7px;">
// Provinces select
<select style="width:100%" class="form-control" name="province_idLocationUpdate" id="province_idLocationUpdate">
#foreach($provinces as $province)
<option value="{{$province->id}}">{{$province->name}}</option>
#endforeach
</select>
<label class="control-label">Province</label>
</div>
<div class="col-md-12 sm-form-design" style="margin-bottom:7px;">
// Cities select
<select style="width:100%" class="form-control" name="city_idLocationUpdate" id="city_idLocationUpdate">
#foreach($cities as $city)
<option value="{{$city->id}}">{{$city->name}}</option>
#endforeach
</select>
<label class="control-label">City</label>
</div>
<div class="col-md-12 sm-form-design" style="margin-bottom:7px;">
<div class="form-group" style="width:100%">
<div class="sm-form-design">
<input style="width:100%" type="text" value="${i.postalCode}" name="postalCodeUpdate" id="postalCodeUpdate" class="form-control" placeholder="Please enter your customer postalC code." required>
<label class="control-label">Postal Code</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row" style="margin-bottom:7px;">
<div class="col-md-3">
<div class="form-group" style="width:100%">
<div class="sm-form-design">
<input type="text" style="width:100%" name="seqNoUpdate" id="seqNoUpdate" value="${i.seqNo}" class="form-control" placeholder="Please enter your location seqNo." required>
<label class="control-label">seqNo</label>
</div>
</div>
</div>
<div class="col-md-9">
<div class="form-group" style="width:100%">
<div class="sm-form-design">
<input type="text" style="width:100%" value="${i.name}" name="nameLocUpdate" id="nameLocUpdate" class="form-control" placeholder="Please enter your location name." required>
<label class="control-label">Name</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" data-id="${i.id}" class="btn locationUpdate btn-success">Update</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- ./Edit -->
<Form id="deleteForm" method="post" action="${url}"> #csrf #method("DELETE")<button type="submit" data-id="${i.id}" class="btn btn-sm customerDelete btn-danger">Delete</button></form>
</td>'
'</tr>`;
$('#table_dataLocations').append(row);
});
// rest of the code
Question
How can I select correct option in my edit form selects?
Update
I added loop to my code like:
$.each(data.cities, function(key, value) {
//value.id == city id
//i.city_id == locations city_id
if(value.id == i.city_id)
{
$('select[name="city_idLocationUpdate"]').append('<option value="'+ value.id +'" selected>'+ value.name +'</option>');
}
else
{
$('select[name="city_idLocationUpdate"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
}
});
This works but the issue with this is for all my locations it gets city of latest row in table and latest row itself is empty.
Example:
locations table::
row 1 = city abc
row 2 = city def
row 3 = city xyz
it shows city xyz for row 1 and 2 but row 3 is empty!
PS: here i shared screen record in case my explanation wasn't
clear enough.
You can do is to separate your table as blade and return it from ajax.
Using blade you can now target selected value.
Route::get('/ajaxTableDelete', 'Controller#myAjax');
public function myAjax() {
$province = $provinceData;
$cities= $cities;
return view('view.deleteTable', ['province'=>$province,'cities'=>$cities]->render();
}
deleteTable.blade.php
// put your table here
Through ajax
success:function(data){
$('#table_dataLocations').append(data);
}
$.each(data.cities, function(key, value) {
$('select[name="city_idLocationUpdate"]')
.append(`<option value="${value.id}" ${value.id == i.city_id ? 'selected' : ''}>${value.name}</option>`)
});
Solved
I gave up on ajax handler and brought back my #foreach to html (same as my first code above)
And then I've changed it like:
#foreach($cities as $city)
<option value="{{$city->id}}" ${`{{$city->id}}` == i.city_id ? 'selected' : ''}>{{$city->name}}</option>
#endforeach
Basically i used my php method in returned html.
${`{{$city->id}}` == i.city_id ? 'selected' : ''}
Hope it helps others.

How to create a simple edit button on crud?

i'm trying to make a simple Crud for my homework . most of my code works properly for the most part, except the edit button. it only edits the first row. below, i provide my TS code along with my HTML. for the HTML i'm using Modal windows. so everytime i click on the edit buttons. a modal will appears
function create() {
let user: string = String($("#username").val());
let data: JQuery = $("<tr id='crudData'><td>" + user + "</td><td><button class='btn btn-info' data-toggle='modal' data-target='#crudModal'>Bearbeiten</button></td></tr>");
$("#crud").append(data);
}
function edit() {
let user2: string = String($("#username2").val());
let data2: JQuery = $("<tr id='crudData'><td>" + user2 + "</td><td><button class='btn btn-info' data-toggle='modal' data-target='#crudModal'>Bearbeiten</button></td></tr>");
$("#crudData").replaceWith(data2);
}
$("#userbstg").on("click", create);
$("#saveEdit").on("click", edit);
<section>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3 class="section-heading">Aufgabe - Usermanager</h3>
<label for="username">Username:</label>
<input id="username" class="form-control col-md-3" type="text">
<button id="userbstg" class="btn btn-info">Add</button>
<table id="crud" class="col-md-4 table">
<tr>
<th class="col-2" id="user">User</th>
<th class="col-2" id="edit"></th>
</tr>
</table>
</div>
</div>
</div>
<div class="modal fade" id="crudModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<label for="username2">Username:</label>
<input id="username2" class="form-control col-md-12" type="text">
<button type="button" id="saveEdit" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
</section>

Change the multi select option text, when the option text is changed jquery

I'm creating a form where the user is allowed to add the options manually to the multiple select box. I've provided a preview field(for showing the preview) and a default value field(to select the default values if the user needs). There is a field for the user to enter the options. Once the user clicks the Add button after entering an option, it will be displayed in div provided. Each option can also be edited.
When the option is Added, that option will be added to the default value field as dropdown and to the preview field as dropdown. This is done simultaneouly, whenever an option is added.
When the option is edited, (according to my logic) the option in the div should be edited and the option in the default value and preview option should be edited as well. This is how I tried:
<div class="modal fade" id="MultiSelect_Modal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog" style="min-width: 75% !important;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="FieldType">Multi Select</h4>
</div>
<div class="modal-body form-horizontal">
<div class="row">
<div class="col-sm-6">
<div class="form-group required">
<label for="MultiSelect_Label" class="col-sm-4 control-label">Label Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="MultiSelect_Label" name="MultiSelect_Label" value=''>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="MultiSelect_DefaultValues" class="col-sm-4 control-label">Default Value</label>
<div class="col-sm-6">
<select id="MultiSelect_DefaultValues" name="MultiSelect_DefaultValues[]" class="form-control" multiple="multiple" style="width: 160px;">
<option value="0">---Select---</option>
</select>
</div>
</div>
</div>
</div>
<div class="row" id="manualEntryDiv">
<div class="col-sm-6">
<div class="form-group required">
<label for="MultiSelect_Options" class="col-sm-4 control-label">Options</label>
<div class="col-sm-6">
<div class="input-group">
<input type="text" class="form-control" id="MultiSelect_Options" name="MultiSelect_Options" value=''>
<span class="input-group-btn">
<input type="button" class="btn btn-primary" id="MultiSelect_optionAdd" name="MultiSelect_optionAdd">
</span>
</div>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="result" id="MultiSelect_mydiv"></div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group" style="margin-left: -20px;">
<label for="MultiSelect_Description" class="col-sm-4 control-label">Description</label>
<div class="col-sm-6">
<textarea type="text" class="form-control" id="MultiSelect_Description" name="MultiSelect_Description" row='3'></textarea>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group required">
<label for="MultiSelect_Status" class="col-sm-4 control-label">Status</label>
<div class="col-sm-6">
<select class="form-control" name="MultiSelect_Status" id="MultiSelect_Status">
<option value="1">Active</option>
<option value="0">In-Active</option>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="MultiSelect_Preview" id="MultiSelect_PreviewID" class="col-sm-4 control-label">Preview</label>
<div class="col-sm-6">
<select id="MultiSelect_Preview" name="MultiSelect_Preview[]" class="form-control" multiple="multiple" style="width: 160px;">
<option value="0">---Select---</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer clearfix">
<button type="button" class="btn btn-default" onclick="clearcontrols();" data-dismiss="modal">Close</button>
<input type="submit" id="MultiSelect_Save" name="MultiSelect_Save" value="Save" class="btn btn-primary">
</div>
</div>
</div>
</div>
$("#MultiSelect_optionAdd").click(function(){
if($("#MultiSelect_Options").val() == ""){
MyNotif.Show("Please enter an option","warning");
} else {
if($("#MultiSelect_optionAdd").val() == "Add"){
var optionvalue = $("#MultiSelect_Options").val();
$("#MultiSelect_mydiv").append("<span id='span" + a + "' class='editbutton'>" + optionvalue + "&nbsp&nbsp&nbsp&nbsp<a href='javascript:void(0)' ><i class='fa fa-close btn btn-danger btn-xs btn-remove btn-icon remove' id='remove" + a + "' style='display: none;'></i></a><a href='javascript:void(0)'><i class='fa fa-pencil btn btn-warning btn-xs btn-edit btn-icon edit' id='edit" + a + "' style='display: none; margin-right:10px;'></i></a></span><br/>");
$("#MultiSelect_Preview").append('<option value="value-'+ optionvalue +'" id="options'+ a +'">' + optionvalue + '</option>');
$("#MultiSelect_DefaultValues").append('<option value="value-'+ optionvalue +'" id="defaultOptions'+ a +'">' + optionvalue + '</option>');
a = a + 1;
$("#MultiSelect_Options").val("");
} else if ($("#MultiSelect_optionAdd").val() == "Update") {
$("#"+spanid).text($("#MultiSelect_Options").val()).append("&nbsp&nbsp&nbsp&nbsp<a href='javascript:void(0)' ><i class='fa fa-close btn btn-danger btn-xs btn-remove btn-icon remove' id='" + removebuttonid + "' style='display: none;'></i></a><a href='javascript:void(0)'><i class='fa fa-pencil btn btn-warning btn-xs btn-edit btn-icon edit' id='" + editbuttonid + "' style='display: none; margin-right:10px;'></i></a>");
$("#MultiSelect_optionAdd").val("Add");
$("#"+optionsid).text($("#MultiSelect_Options").val());
$("#"+defaultOptionsid).text($("#MultiSelect_Options").val());
$("#"+defaultOptionsid).val("value-"+$("#MultiSelect_Options").val());
$("#MultiSelect_Options").val("");
}
$('.remove').click(function(){
removebuttonid = $(this).attr("id");
spanid = removebuttonid.replace('remove', 'span');
optionsid = removebuttonid.replace('remove', 'options');
defaultOptionsid = removebuttonid.replace('remove', 'defaultOptions');
$("#"+spanid).next("br").remove();
$("#"+spanid).remove();
$("#"+optionsid).remove();
$("#"+defaultOptionsid).remove();
});
$(".edit").click(function(){
addButtonValue = "Update"
$("#MultiSelect_optionAdd").val(addButtonValue);
editbuttonid = $(this).attr("id");
spanid = editbuttonid.replace('edit', 'span');
optionsid = editbuttonid.replace('edit', 'options');
defaultOptionsid = editbuttonid.replace('edit', 'defaultOptions');
removebuttonid = editbuttonid.replace('edit', 'remove');
var value = ($("#"+spanid).text()).trim();
$("#MultiSelect_Options").val(value);
});
}
});
Here, whenever I add an option, that option gets added to the div, default value and preview fields. Whatever I add as an option, it gets added.
But, the problem is, when I edit the option I provide, the option inside the div gets changed. But, the option in the default value and preview displays the same text which was provided previously. But, when I inspect the element, I can see the edited text as well as edited value. But, the previously provided option is only shown. The edited text is not shown.
I don't know what's wrong with the above code. What should I change in this?

Bootstrap Modal issue with fileinput

I have a real interesting problem with a bootstrap modal, let's start from beginning.
I have a list of inventories - with the function that you can book, edit, view, and delete. See image
All my functions works except edit, the problem I have with edit is that I can only edit one item before a page refresh. If I click edit on the first row that image shown is used on any subsequent edit I do - if I click the 2 or 3 row edit I get the first image - see popup image
This is the javascript to call the modal to pop up, as you can see I'm clearing the form first - making an Ajax call to get the data for that button. I only have a problem with an image not being able to show the actual image for an item.
//
// Edit the inventory
//
function edit_inventory(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('[name="image_name]').empty();
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('warehouse/inventory/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
var previewimage = data.image_name;
$('[name="image_name]').val(data.image_name);
$('[name="id"]').val(data.id);
$('[name="user_id"]').val(data.user_id);
$('[name="name"]').val(data.name);
$('[name="description"]').val(data.description);
$('[name="type_id"]').val(data.type_id);
$('[name="certifications_id"]').val(data.certifications_id);
$('[name="condition_id"]').val(data.condition_id);
$('[name="location_id"]').val(data.location_id);
$('[name="location_in_warehouse"]').val(data.location_in_warehouse);
$('[name="quantity_id"]').val(data.quantity_id);
$('[name="size_id"]').val(data.size_id);
$('[name="skills_required_id"]').val(data.skills_required_id);
$('[name="use_id"]').val(data.use_id);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Inventory'); // Set title to Bootstrap modal title
$("#image_name").fileinput({
uploadUrl: "<?php echo site_url('warehouse/inventory/ajax_fileupload')?>",
deleteUrl: "<?php echo site_url('warehouse/inventory/ajax_deletefile')?>",
showUpload: true,
uploadAsync: true,
// your upload server url
allowedFileExtensions : ['jpg', 'jpeg', 'png','gif'],
overwriteInitial: false,
maxFileSize: 1000,
minFileCount: 1,
maxFileCount: 5,
maxFilesNum: 10,
initialPreview: [
// IMAGE DATA
"<?php echo site_url('assets/uploads/')?>/" + previewimage,
],
initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
initialPreviewFileType: 'image', // image is the default and can be overridden in config below
initialPreviewConfig: [
{caption: previewimage, size: 576237, width: "120px", url: "warehouse/inventory/ajax_fileupload", key: 1},
],
layoutTemplates: {
main1: "{preview}\n" +
"<div class=\'input-group {class}\'>\n" +
" <div class=\'input-group-btn\'>\n" +
" {browse}\n" +
" {upload}\n" +
" {remove}\n" +
" </div>\n" +
" {caption}\n" +
"</div>"
}
});
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
For each item that I select to edit, I'm calling the backend to get the latest image from the database, each time a new image name is set in
var previewimage = data.image_name;
For the file input, I'm using the krajee bootstrap fileinput library, as I need to upload images. http://plugins.krajee.com/file-input/demo
You would expect by adding the new previewimage variable to the
initialPreview: [
// IMAGE DATA
"<?php echo site_url('assets/uploads/')?>/" + previewimage,
],
It would show a different image - somehow the first edit click done that image resides in the modal and is not cleared.
I have tried several things to clear the modal e.g.
$('#image_name').val('');
$('form').find('input[type=file]').val('');
Nothing works, it seems that I'm not getting the right element to clear or there is something in the krajee bootstrap file input that is not cleared correctly.
This is the code for my modal
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Inventory Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal" role="form" data-toggle="validator">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label">Select File</label>
<div class="col-md-9">
<input id="image_name" name="image_name[]" type="file" multiple class="file-loading">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Name</label>
<div class="col-md-9">
<input name="name" placeholder="Item Name" class="form-control" type="text" data-validate="true" data-error="Required Field" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Description</label>
<div class="col-md-9">
<input name="description" placeholder="Give a Description" class="form-control" type="text" data-validate="true" data-error="Required Field" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Location in Warehouse</label>
<div class="col-md-9">
<input name="location_in_warehouse" placeholder="Give details on were to find in Warehouse" class="form-control" type="text" data-validate="true" data-error="Required Field" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Type</label>
<div class="col-md-9">
<select id="types" name="type_id" class="form-control">
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Usage</label>
<div class="col-md-9">
<select id="usages" name="use_id" class="form-control">
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Skills Required</label>
<div class="col-md-9">
<select id="skills" name="skills_required_id" class="form-control">
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Certifications</label>
<div class="col-md-9">
<select id="certificates" name="certifications_id" class="form-control">
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Location</label>
<div class="col-md-9">
<select id="locations" name="location_id" class="form-control">
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Quantity</label>
<div class="col-md-9">
<input name="quantity_id" placeholder="Quantity" class="form-control" type="number" data-validate="true" data-error="Only numbers allowed" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Condition</label>
<div class="col-md-9">
<select id="conditions" name="condition_id" class="form-control">
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Item Size</label>
<div class="col-md-9">
<input name="size_id" placeholder="Enter a size of the item" class="form-control" type="text">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
I appreciate any help or suggestion to resolve this issue.
Here is the server side code:
switch ($inventory->status) {
case '0':
$row[] = '<img alt="sign in" src="' . base_url() . 'assets/uploads/warehousein.png">';
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Book" onclick="book_inventory('."'".$inventory->id."'".')"><i class="glyphicon glyphicon-check"></i> Book</a>
<a class="btn btn-sm btn-success" href="javascript:void(0)" title="Edit" onclick="edit_inventory('."'".$inventory->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
<a class="btn btn-sm btn-info" href="javascript:void(0)" title="View" onclick="view_inventory('."'".$inventory->id."'".')"><i class="glyphicon glyphicon-list-alt"></i> View</a>
<a class="btn btn-sm btn-danger" href="javascript:void(0)" title="delete" onclick="delete_inventory('."'".$inventory->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
break;
As you can see, I add the inventory->id to the button.
just put this code first before you declare file input
$('#selector').fileinput('destroy');

Categories

Resources