Regarding Vue function in dashboard - laravel

We are experiencing problems after a Vue update. However, we cannot locate the error. Could anyone help us find this problem? This has occurred in the dashboard at a certain section where we show the payments from our users, so the admins can look into this.
The code:
addCollection: function (employee) {
var self = this;
year = 0;
var selectText =
'<div class="swal2-content" style="display: block;">Periode:</div>';
selectText +=
'<select id="swal-select1" class="swal2-select form-control" style="display: inline-block; width: calc(50% - 4px); margin-right: 4px;">';
for (year in self.vmAvailableYears) {
alert(this.year);
selectText +=
'<option value="' +
self.vmAvailableYears[year] +
'" ' +
(self.vmAvailableYears[year] == self.vmCurrentYear
? "selected"
: "") +
">" +
self.vmAvailableYears[year] +
"</option>";
}
selectText += "</select>";
selectText +=
'<select id="swal-select2" class="swal2-select form-control" style="display: inline-block; width: calc(50% - 4px); margin-left: 4px;">';
for (i = 1; i < 52; i++) {
selectText +=
'<option value="' +
i +
'" ' +
(i == self.vmCurrentWeek ? "selected" : "") +
">week " +
i +
"</option>";
}
selectText += "</select>";
selectText +=
'<div class="swal2-content" style="display: block;">Type:</div>';
selectText +=
'<select id="swal-select3" class="swal2-select form-control">';
selectText +=
'<option value="rent" style="' +
(self.vmCanAlter ? "" : "display: none;") +
'" data-amount-required="true" data-comment-required="false">Huur</option>';
selectText +=
'<option value="addition" data-amount-required="true" data-comment-required="true">Extra kosten</option>';
selectText +=
'<option value="payment_cash" selected data-amount-required="true" data-comment-required="false">Betaling contant</option>';
selectText +=
'<option value="payment_card" data-amount-required="true" data-comment-required="false">Betaling PIN</option>';
selectText +=
'<option value="payment_transfer" data-amount-required="true" data-comment-required="false">Betaling overboeking</option>';
selectText +=
'<option value="vacation_unpaid" data-amount-required="false" data-comment-required="false">Vakantie (doorbetalen)</option>';
selectText +=
'<option value="vacation_paid" data-amount-required="false" data-comment-required="false">Vakantie (niet doorbetalen)</option>';
selectText +=
'<option value="remission" data-amount-required="true" data-comment-required="true">Kwijtschelding</option>';
selectText +=
'<option value="comment" data-amount-required="false" data-comment-required="true">Opmerking</option>';
selectText += "</select>";
selectText +=
'<div id="swal-label1" class="swal2-content" style="display: block;">Bedrag:</div>';
selectText +=
'<input id="swal-input1" class="swal2-input" placeholder="Bedrag">';
selectText +=
'<div class="swal2-content" style="display: block;">Opmerking (<span id="swal-comment-label">optioneel</span>):</div>';
selectText +=
'<input id="swal-input2" class="swal2-input" placeholder="Opmerking">';
self
.$swal({
title:
employee.firstname +
" " +
employee.insertion +
" " +
employee.lastname,
html: selectText,
showCancelButton: true,
confirmButtonText: "Toevoegen",
cancelButtonText: "Annuleren",
showLoaderOnConfirm: true,
allowOutsideClick: false,
onOpen: function (el) {
$(el)
.find("#swal-select3")
.on("change", function () {
var selectedOption = $("option:selected", this);
var amountRequired = selectedOption.data("amount-required");
var commentRequired = selectedOption.data("comment-required");
var amountLabel = $("#swal-label1");
var amountInput = $("#swal-input1");
var commentInput = $("#swal-input2");
if (amountRequired) {
amountLabel.show();
amountInput.show();
} else {
amountLabel.hide();
amountInput.val("");
amountInput.hide();
}
commentInput.prop("required", commentRequired);
$("#swal-comment-label").text(
commentRequired ? "verplicht" : "optioneel"
);
});
$(el)
.find("#swal-select1, #swal-select2")
.on("change", function () {
const rentOption = $('#swal-select3 option[value="rent"]');
if (
self.vmCanAlter ||
self.weekIsInFuture(
$("#swal-select1").val(),
$("#swal-select2").val()
)
) {
rentOption.show();
} else {
rentOption.hide();
if ($("#swal-select3").val() == "rent") {
$("#swal-select3").val("payment_cash");
}
}
});
},
preConfirm: function (key) {
return new Promise(function (resolve, reject) {
if (
$("#swal-input2").prop("required") &&
$("#swal-input2").val().length <= 0
) {
reject("Opmerking is een verplicht veld.");
}
var postData = {
employee_id: employee.id,
type: $("#swal-select3").val(),
amount: $("#swal-input1").val().replace(",", "."),
comment: $("#swal-input2").val(),
year: $("#swal-select1").val(),
week: $("#swal-select2").val(),
};
self.resourceCollection.store(postData).then(
(response) => {
handleRequestSuccess(response);
resolve(response.data);
},
(response) => {
let handledResponse = handleRequestError(response);
if (handledResponse) {
reject(self.formatErrors(response.data));
}
}
);
});
},
})
.then(
(response) => {
let amount = parseFloat(response.amount);
if (["rent", "addition"].indexOf(response.type) > -1) {
employee.balance -= amount;
} else {
employee.balance += amount;
}
if (response.rent_subtract > 0) {
employee.collections.filter((collection) => {
employee.balance += parseFloat(collection.amount);
if (collection.type === "rent") {
collection.amount = 0;
}
});
}
employee.collections.push({
year: response.year,
week: response.week,
type: response.type,
amount: response.amount,
comment: response.comment,
admin: response.admin,
});
},
(rejection) => {}
);
}
The error:
[Vue warn]: Error in v-on handler: "ReferenceError: Can't find variable: year"
found in
---> <NdAdminCollectionEmployee> at resources/assets/js/vue/views/admin/collection/NdAdminCollectionEmployee.vue
<Root>
The other error:
ReferenceError: Can't find variable: year —
Kind regards,
Daan IV & Collin III

Related

My geojson polygon doesn't appear on the ajax-leaflet map

This is my first time to make a GIS app with CodeIgniter, Leaflet, and Ajax. I want to show a polygon above my map with geojson file that I've made using geojson.io but the polygon doesn't show. When I inspect the page in my browser it shows an error message like
Failed to load modules/jenis_hutan/...geojson/map.geojson:1
resource: the server responded with a status of 404()
Here is my js code to show the geojson file.
let tnSelect = $("#tn-select");
let gisCard = $("#gis-card");
let divModal = $(".div-modal");
tnSelect.change(function () {
let $val = $(this).val();
loadPage();
setCookie("tn_value", $val, 0.0833333);
window.location.reload(true);
});
$(window).on("load", function () {
let $tn_val = getCookie("tn_value");
let gisMap;
$.ajax({
method: "GET",
url: base_url + "ajax/tn_data",
dataType: "JSON",
data: {},
success: (res) => {
console.log(res);
if ($tn_val !== null) {
for (let i = 0; i < res.length; i++) {
let data = res[i];
let name = data.tn_name;
name = name.replace(
/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g,
function (letter) {
return letter.toUpperCase();
}
);
if (data.tn_id == $tn_val) {
tnSelect.append(
'<option selected id="tn_name" value="' +
data.tn_id +
'">' +
name +
"</option>"
);
gisCard.html(
'<div class="card mb-4 gis-card">' +
'<div class="card-header py-3 text-center">' +
'<h6 class="m-0 font-weight-bold text-center">' +
name +
"</h6>" +
"</div>" +
'<div class="card-body" id="gis-map"></div>' +
"</div>"
);
gisMap = L.map("gis-map").setView([data.tn_lat, data.tn_long], 12);
mapAPI.addTo(gisMap);
} else {
tnSelect.append(
'<option value="' + data.tn_id + '">' + name + "</option>"
);
}
}
} else {
for (let i = 0; i < res.length; i++) {
let data = res[i];
let name = data.tn_name;
name = name.replace(
/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g,
function (letter) {
return letter.toUpperCase();
}
);
if (i < 1) {
tnSelect.append(
'<option selected id="tn_name" value="' +
data.tn_id +
'">' +
name +
"</option>"
);
gisCard.html(
'<div class="card mb-4 gis-card">' +
'<div class="card-header py-3 text-center">' +
'<h6 class="m-0 font-weight-bold text-center">' +
name +
"</h6>" +
"</div>" +
'<div class="card-body" id="gis-map"></div>' +
"</div>"
);
gisMap = L.map("gis-map").setView([data.tn_lat, data.tn_long], 12);
mapAPI.addTo(gisMap);
} else {
tnSelect.append(
'<option value="' + data.tn_id + '">' + name + "</option>"
);
}
}
}
//**//
$.getJSON(base_url + "modules/jenis_hutan/geojson/map.geojson", function (
data
) {
geoLayer = L.geoJson(data, {
style: function (feature) {
return {
fillOpacity: 0.5,
weight: 1,
opacity: 1,
color: "#fa7268",
};
},
onEachFeature: function (feature, layer) {
var kode = feature.properties.kode;
var info_zona = "<h5 style='text-align:left'>ZONA INTI</h5>";
info_zona += "<hr>";
info_zona +=
"<div style='width:100%;text-align:left;margin-top:10px;'><h6>Luas area: 10.475 ha</h6><br><h6>Fungsi zona: Jalur pendakian</h6></div>";
layer.bindPopup(info_zona, {
maxWidth: 260,
closeButton: true,
offset: L.point(0, -20),
});
layer.on("click", function () {
layer.openPopup();
});
},
}).addTo(map);
});
},
});
});
Is there something wrong with my code? This is my college task and the deadline is this Friday so please anyone enlight me:( or at least give me link to some tutorial related to this thing:( Thank you everyone.

Sweetalert2 input validation with AJAX

I'm using sweetalert2 to set-up multiple inputs as modal (with swal mixin), and I need to verify in server-side if values sent are equal to the ones in database. As example I'm using just a constant value in the .php file. Here's my code:
{
onBeforeOpen: function (dom) {
dom.getElementsByClassName('swal2-input')[0].style = "display: none";
},
html:
"<form action='' method='post'>" +
"<div class='main-cont'>"+
"<span>" +
"Por favor ingresa el codigo de verificacion NUIP "+
"que hemos enviado a tu celular" +
"</span>"+
"<div class='row cuadros'>" +
"<input id='num-1' class='inp-num' data-pos='0' type='text' maxlength='1' name='one' onkeypress='isInputNumber(event)' autofocus='autofocus'/>" +
"<input id='num-2' class='inp-num' data-pos='1' type='text' maxlength='1' name='two' onkeypress='isInputNumber(event)'>" +
"<input id='num-3' class='inp-num' data-pos='2' type='text' maxlength='1' name='three' onkeypress='isInputNumber(event)'>" +
"<input id='num-4' class='inp-num' data-pos='3' type='text' maxlength='1' name='four' onkeypress='isInputNumber(event)'>" +
"</div>" +
"</div>"+
"</form>",
inputValidator: function() {
var nums = Object.values(document.getElementsByClassName("inp-num"));
for(var i = 0; i < nums.length; i++) {
if(!nums[i].value) {
return 'Ingresa el codigo completo';
}
}
$.ajax({
type: "POST",
url: "php/confirma_datos.php",
data: {
"one": $("#num-1").val(),
"two": $("#num-2").val(),
"three": $("#num-3").val(),
"four": $("#num-4").val(),
},
success : function(response) {
if (response == 'true') {
swal('hola');
return 'OK';
} else {
console.log('no coinciden');
}
},
});
},
preConfirm: function () {
return [
$("#num-1").val(),
$("#num-2").val(),
$("#num-3").val(),
$("#num-4").val(),
]
},
},
And in the server side I have.
<?php
$nuip_comp = "1234";
$nuip = $_POST['one'] . "" . $_POST['two'] . "" . $_POST['three']. "" . $_POST['four'] ;
if($nuip_comp == $nuip) {
echo 'true';
} else {
echo 'false';
}
I want to prevent the modal to go to the next step until the values are equal. Any idea on how to do this?
Thanks!

Is it possible to leverage one template and one uploader/java scipt for multiple instances of uploader?

This may be TOO much to ask, but I still want to ask as it looks like too much code on web pages.
I have following template and javascript for a single instance of uploader. In my case, I have to use 8 uploader instances in a page (ofcourse in tabs!). If at all possible, I DO NOT want to repeat below code chunks to all 8 uploaders. Is is possible to leverage code (template,javascript) for all uploaders.
Please see my javascript that I am trying to re-use; but on the execution it fails for ...Uncaught Error: Method ....jsonStringCreatedByMyFunction - see my json string below..... does not exist on jQuery.fineUploader
template:
<script type="text/template" id="qq-template-manual-trigger-section1">
<div class="qq-uploader-selector qq-uploader" qq-drop-area-text="Drop files here">
<div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
<div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
</div>
<div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
<span class="qq-upload-drop-area-text-selector"></span>
</div>
<div class="buttons">
<div class="qq-upload-button-selector qq-upload-button">
<div>Select files</div>
</div>
<button type="button" id="trigger-upload-section1" class="btn btn-primary">
<i class="icon-upload icon-white"></i> Upload
</button>
</div>
<span class="qq-drop-processing-selector qq-drop-processing">
<span>Processing dropped files...</span>
<span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
</span>
<ul class="qq-upload-list-selector qq-upload-list" aria-live="polite" aria-relevant="additions removals">
<li>
<div class="qq-progress-bar-container-selector">
<div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div>
</div>
<span class="qq-upload-spinner-selector qq-upload-spinner"></span>
<div>
<img class="qq-thumbnail-selector" qq-max-size="80" qq-server-scale>
<span class="qq-upload-file-selector qq-upload-file"></span>
<span class="qq-upload-size-selector qq-upload-size"></span>
<span class="qq-edit-filename-icon-selector qq-edit-filename-icon qq-editable" aria-label="Edit filename"></span>
<input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
</div>
<span class="qq-upload-caption-selector qq-upload-caption"></span>
<span class="qq-edit-caption-icon-selector qq-edit-caption-icon kk-editable" aria-label="Edit caption"></span>
<input class="qq-edit-caption-selector qq-edit-caption kk-editing" placeholder="Caption here ..." tabindex="0" type="text">
<button type="button" class="qq-btn qq-upload-delete-selector qq-upload-update-caption" onclick="captionUpdate(true);">Update Caption</button>
<button type="button" class="qq-btn qq-upload-cancel-selector qq-upload-cancel">Cancel</button>
<button type="button" class="qq-btn qq-upload-retry-selector qq-upload-retry">Retry</button>
<button type="button" class="qq-btn qq-upload-delete-selector qq-upload-delete" onclick="captionUpdate(false);">Delete</button
<span role="status" class="qq-upload-status-text-selector qq-upload-status-text"></span>
</li>
</ul>
</div>
</script>
Javascript:
function getFineUploaderJsonObjectStr(sectionInd) {
var requestObj = new Object();
requestObj.endpoint = 'http://s3.amazonaws.com/mybucket';
requestObj.accessKey = 'AKvcccccvccvBIA';
var objectPropertiesObj = new Object();
objectPropertiesObj.key = " function (fileId) { " +
" return $('#login_name').val()+ '/' + $('#book_id).val() + '/' " + sectionInd + " '/' + $('#fine-uploader-manual-trigger-" + sectionInd + " ').fineUploader('getName',fileId); " +
" } ";
var signatureObj = new Object();
signatureObj.endpoint = "http://localhost/app/ci/fine/endpoint";
var uploadSuccessObj = new Object();
uploadSuccessObj.endpoint = "http://localhost/app/ci/fine/endpoint?success";
var uploadSuccessObjParams = new Object();
uploadSuccessObjParams.isBrowserPreviewCapable = qq.supportedFeatures.imagePreviews;
uploadSuccessObjParams.bookid = " function() { return $('#book_id').val(); } ";
uploadSuccessObjParams.sectionid = " function() { return $('#section_id').val(); } ";
uploadSuccessObjParams.section = " function() { return 'section1'; } ";
uploadSuccessObj.params = uploadSuccessObjParams;
var sessionObj = new Object();
sessionObj.endpoint = "http://localhost/app/ci/fine/endpoint?filelist";
var sessionObjParams = new Object();
sessionObjParams.key = " function() { " +
" return $('#login_name').val()+ '/' + $('#book_id').val() + '/' " + sectionInd + " ; " +
" } ";
sessionObj.params = sessionObjParams;
var iframeSupportObj = new Object();
iframeSupportObj.localBlankPagePath = "success.html";
var corsObj = new Object();
corsObj.expected = true;
var chunkingObj = new Object();
chunkingObj.enabled = true;
var resumeObj = new Object();
resumeObj.enabled = true;
var deleteFileObj = new Object();
deleteFileObj.enabled = true;
deleteFileObj.method = "POST";
deleteFileObj.endpoint = "http://localhost/app/ci/fine/endpoint";
var deleteFileParams = new Object();
deleteFileParams.qqcaption = " function() { if (isCaptionUpdate === true) { return captionValue; } } ";
deleteFileParams.bookid = " function() { return $('#book_id').val(); } ";
deleteFileParams.sectionid = " function() { return $('#section1_id').val(); } ";
deleteFileObj.params = deleteFileParams;
var validationObj = new Object();
validationObj.itemLimit = 500;
validationObj.sizeLimit = 15000000;
var thumbnailsObj = new Object();
var thumbnailsObjPlaceholders = new Object();
thumbnailsObjPlaceholders.notAvailablePath = "http://localhost/app/ci/s3.fine-uploader/placeholders/not_available-generic.png";
thumbnailsObjPlaceholders.waitingPath = "http://localhost/app/ci/s3.fine-uploader/placeholders/waiting-generic.png";
thumbnailsObj.placeholders = thumbnailsObjPlaceholders;
var callbacksObj = new Object();
callbacksObj.onComplete = " function(id, name, response) { " +
" if (response.success) { " +
" setSectionImageCount('1', 'U', 0); " +
" } " +
" } ";
callbacksObj.onError = " function(id, name, errorReason, xhrOrXdr) { " +
" if (!isCaptionUpdate) {//isCaptionUpdate will return 206 " +
" alert(qq.format('Error on file number {} - {}. Reason: {}', id, name, errorReason)); " +
" } " +
" } ";
callbacksObj.onUpload = " function(id, fileName) { " +
" captionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; " +
" this.setParams({'qqcaption':captionValue}); " +
" } ";
callbacksObj.onDelete = " function(id) { " +
" captionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; " +
" //change sttaus to 'Updating..' if it is Caption update " +
" var statusSpan = qq(this.getItemByFileId(id)).getByClass('qq-upload-status-text')[0]; " +
" if (isCaptionUpdate === true) { " +
" statusSpan.innerText = 'Updating...'; " +
" } " +
" } ";
callbacksObj.onDeleteComplete = " function(id, xhr, isError) { " +
" if (!isError) { " +
" setSectionImageCount('1', 'D', 0); " +
" } else if (isCaptionUpdate === true) { " +
" statusSpan.innerText = ''; " +
" } " +
" } ";
callbacksObj.onSubmitted = " function (id, name) { " +
" //nothing " +
"} ";
callbacksObj.onStatusChange = " function(id, oldStatus, newStatus) { " +
" if (oldStatus === 'submitting' && newStatus === 'submitted'){ " +
" //hide 'Update Caption' btn for uploading files " +
" var updateCaptionBtn = qq(this.getItemByFileId(id)).getByClass('qq-upload-update-caption')[0]; " +
" qq(updateCaptionBtn).hide(); " +
" } " +
" } ";
callbacksObj.onSessionRequestComplete = " function(response, success, xhrOrXdr) { " +
" //alert(response.length); uploaded file count should be added to it; " +
" if (success) { " +
" if (response.length > 0) { " +
" //$('#section1ImageCount').text(response.length); " +
" setSectionImageCount('1', 'I', response.length); " +
" } " +
" var uploader = this; " +
" response.forEach(function(item) { " +
" var id = uploader.getUploads({uuid: item.uuid}).id; " +
" var fileEl = uploader.getItemByFileId(id); " +
" fileEl.querySelector('.qq-edit-caption').value = item.qqcaption; " +
" }) " +
" } " +
" } ";
var wrapperObj = new Object();
wrapperObj.template = 'qq-template-manual-trigger-'+sectionInd;
//wrapperObj.template = 'qq-template-manual-trigger';
wrapperObj.autoUpload = false;
wrapperObj.debug = true;
wrapperObj.request = requestObj;
wrapperObj.objectProperties = objectPropertiesObj;
wrapperObj.signature = signatureObj;
wrapperObj.uploadSuccess = uploadSuccessObj;
wrapperObj.session = sessionObj;
wrapperObj.iframeSupport = iframeSupportObj;
wrapperObj.cors = corsObj;
wrapperObj.chunking = chunkingObj;
wrapperObj.resume = resumeObj;
wrapperObj.deleteFile = deleteFileObj;
wrapperObj.validation = validationObj;
wrapperObj.thumbnails = thumbnailsObj;
wrapperObj.callbacks = callbacksObj;
var jsonString = JSON.stringify(wrapperObj);
console.log(jsonString);
return jsonString;
};
var section1JsonStr = getFineUploaderJsonObjectStr('section1');
var section2JsonStr = getFineUploaderJsonObjectStr('section2');
$('#fine-uploader-manual-trigger-section1').fineUploaderS3(section1JsonStr);
$('#fine-uploader-manual-trigger-section2').fineUploaderS3(section2JsonStr);
$('#trigger-upload-section1').click(function() {
$('#fine-uploader-manual-trigger-section1').fineUploaderS3('uploadStoredFiles');
});
$('#trigger-upload-section2').click(function() {
$('#fine-uploader-manual-trigger-section2').fineUploaderS3('uploadStoredFiles');
});
jsonStringCreatedByMyFunction:
{"template":"qq-template-manual-trigger-section1","autoUpload":false,"debug":true,"request":{"endpoint":"http://s3.amazonaws.com/mybucket","accessKey":"AKvvvvhjjjjAABIA"},"objectProperties":{"key":" function (fileId) { \treturn $('#login_name').val()+ '/' + $('#book_id).val() + '/' section1 '/' + $('#fine-uploader-manual-trigger-section1 ').fineUploader('getName',fileId); } "},"signature":{"endpoint":"http://localhost/app/ci/fine/endpoint"},"uploadSuccess":{"endpoint":"http://localhost/app/ci/fine/endpoint?success","params":{"isBrowserPreviewCapable":true,"bookid":" function() { return $('#book_id').val(); } ","sectionid":" function() { return $('#section_id').val(); } ","section":" function() { return 'section1'; } "}},"session":{"endpoint":"http://localhost/app/ci/fine/endpoint?filelist","params":{"key":" function() { \treturn $('#login_name').val()+ '/' + $('#book_id').val() + '/' section1 ; } "}},"iframeSupport":{"localBlankPagePath":"success.html"},"cors":{"expected":true},"chunking":{"enabled":true},"resume":{"enabled":true},"deleteFile":{"enabled":true,"method":"POST","endpoint":"http://localhost/app/ci/fine/endpoint","params":{"qqcaption":" function() { if (isCaptionUpdate === true) { return captionValue; } } ","bookid":" function() { return $('#book_id').val(); } ","sectionid":" function() { return $('#section1_id').val(); } "}},"validation":{"itemLimit":500,"sizeLimit":15000000},"thumbnails":{"placeholders":{"notAvailablePath":"http://localhost/app/ci/s3.fine-uploader/placeholders/not_available-generic.png","waitingPath":"http://localhost/app/ci/s3.fine-uploader/placeholders/waiting-generic.png"}},"callbacks":{"onComplete":" function(id, name, response) { \tif (response.success) { \t\tsetSectionImageCount('1', 'U', 0); \t} } ","onError":" function(id, name, errorReason, xhrOrXdr) { \tif (!isCaptionUpdate) {//isCaptionUpdate will return 206 \t\talert(qq.format('Error on file number {} - {}. Reason: {}', id, name, errorReason)); \t} } ","onUpload":" function(id, fileName) { \tcaptionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; \tthis.setParams({'qqcaption':captionValue}); } ","onDelete":" function(id) { \tcaptionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; \t//change sttaus to 'Updating..' if it is Caption update \tvar statusSpan = qq(this.getItemByFileId(id)).getByClass('qq-upload-status-text')[0]; \tif (isCaptionUpdate === true) { \t\tstatusSpan.innerText = 'Updating...'; \t} } ","onDeleteComplete":" function(id, xhr, isError) { \tif (!isError) { \t\tsetSectionImageCount('1', 'D', 0); \t} else if (isCaptionUpdate === true) {\t\t\tstatusSpan.innerText = ''; \t} } ","onSubmitted":" function (id, name) { //nothing } ","onStatusChange":" function(id, oldStatus, newStatus) { \tif (oldStatus === 'submitting' && newStatus === 'submitted'){ \t\t//hide 'Update Caption' btn for uploading files \t\tvar updateCaptionBtn = qq(this.getItemByFileId(id)).getByClass('qq-upload-update-caption')[0]; \t\tqq(updateCaptionBtn).hide(); \t} } ","onSessionRequestComplete":" function(response, success, xhrOrXdr) { \t//alert(response.length); uploaded file count should be added to it; \tif (success) { \t\t\t\tif (response.length > 0) { \t\t\t//$('#section1ImageCount').text(response.length); \t\t\tsetSectionImageCount('1', 'I', response.length); \t\t} \t\tvar uploader = this;\t \t\tresponse.forEach(function(item) { \t\t\tvar id = uploader.getUploads({uuid: item.uuid}).id; \t\t\tvar fileEl = uploader.getItemByFileId(id); \t\t\tfileEl.querySelector('.qq-edit-caption').value = item.qqcaption; \t\t}) \t} } "}}

Default value of drop-down list with JavaScript and JSON

I have a City field in my form when user select his province/state a drop-down list of cities appear according to selected state. However for the cities list there is no default value like 'Select your city'. I want to add this value.
Below is my field.js :
function getAjaxReqest(action, selectCountry, stateId, normalImput,selectedCity) {
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('billing:city').replace('<select id="billing:city" name="billing[city]" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this,selectedCity) +
'</select>');
},
onFailure: $('billing:city').replace(normalImput),
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function getAjaxReqestCustomer(action, selectCountry, stateId, normalImput, selectedCity) {
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('city').replace('<select id="city" name="city" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this, selectedCity) +
'</select>');
},
onFailure: $('city').replace(normalImput),
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function getAjaxReqestShip(action, selectCountry, stateId, normalImput,selectedCity) {
if (normalImput != null) {
var resetShip = true;
} else {
var resetShip = false;
}
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('shipping:city').replace('<select id="shipping:city" name="shipping[city]" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this,selectedCity) +
'</select>');
},
onFailure: function (resetShip) {
if (resetShip) {
$('shipping:city').replace(normalImput)
}
},
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function convertJsonToHtml(data, ship, selectedCity) {
var jsonData = data.evalJSON();
if (jsonData.length == 0) {
ship.replace(normalImput);
return;
}
console.log(jsonData);
htmlData = '';
jsonData.each(function (item) {
if (item.cityname == selectedCity) {
htmlData += '<option value="' + item.cityname + '" selected>' + item.cityname + '</option>';
} else {
htmlData += '<option value="' + item.cityname + '">' + item.cityname + '</option>';
}
});
return htmlData;
}
While the following code generates the City field on frontend in the form.
<div class="input-box">
<input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]"
value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"
class="input-text <?php echo $this->helper('customer/address')->getAttributeValidationClass('city') ?>"
id="billing:city"/>
</div>
Any help and tips are appreciated.I am a novice in Javascript and JSON so i am having a hard time playing with it.
EDIT:
I tried this:
div class="input-box">
<input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]"
value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"
class="input-text <?php echo $this->helper('customer/address')- >getAttributeValidationClass('city') ?>"
id="billing:city"/>
<select name="anything"><option value="undefined" disabled="selected">Select your city</option></select>
</div>
This works but adds the text 'Select your city' below the city field NOT inside it.
use this code as default showing before selecting city (i.e)set value as "undefined" disabled selected.
' +
'Select your city' + convertJsonToHtml(data.responseText, this, selectedCity) +
''

jqgrid - resize columns doesn't work in bootstrap modal

based of this answer
I have a bootstrap modal that I used that function for that.
Here is the code:
Modal view file:
<div class="modal modal-wide fade" id="mo-selector-dialog" title="<bean:message key="add.ex"/>">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add</h4>
</div>
<div class="modal-body">
<table id="moTable"></table>
<!-- <div id="pager"></div>-->
<div class="modal-footer">
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Modal call in js file:
$('#add-link').click(function(){
$('#mo-selector-dialog').css("display", "block");
$('.mo-backdrop').css("display", "block");
mc$('#mo-selector-dialog').modal({show:true});
$('body').css("overflow-y", "hidden");
});
jqgrid:
$moGrid.bind("jqGridAfterLoadComplete jqGridRemapColumns", function () {
var $this = $(this),
$cells = $this.find(">tbody>tr.jqgrow>td"),
$colHeaders = $($.map(this.grid.headers, function (item) { return item.el; })).find(">div"),
colModel = $this.jqGrid("getGridParam", "colModel"),
cellLayout = $this.jqGrid("getGridParam", "cellLayout"),
iCol,
iRow,
rows,
row,
n = $.isArray(colModel) ? colModel.length : 0,
cm,
colWidth,
idColHeadPrexif = "jqgh_" + this.id + "_";
$cells.wrapInner("<span class='mywrapping'></span>");
$colHeaders.wrapInner("<span class='mywrapping'></span>");
for (iCol = 0; iCol < n; iCol++) {
cm = colModel[iCol];
if (cm.hidden) {
continue;
}
colWidth = $("#" + idColHeadPrexif + $.jgrid.jqID(cm.name) + ">.mywrapping").outerWidth(true) + 25; // 25px for sorting icons
for (iRow = 0, rows = this.rows; iRow < rows.length; iRow++) {
row = rows[iRow];
if ($(row).hasClass("jqgrow")) {
colWidth = Math.max(colWidth, $(row.cells[iCol]).find(".mywrapping").outerWidth(true));
}
}
$this.jqGrid("setColWidth", iCol, colWidth + ($.jgrid.cell_width? cellLayout: 0));
}
});
$moGrid.jqGrid({
height: 400,
url: 'ex/list',
sortname: 'bDt',
colNames: IS.mo.columnDisplayNames,
colModel: IS.mo.colModelDef,
beforeSelectRow: shiftSelect,
gridview: true,
rowattr: function (rd) {
return rowStyle(rd);
},
beforeRequest: IS.filter.applyFilter($moGrid, $('input, select', filterForm), IS.mo.listFilterValues),
onSelectRow: function(id, status) {
$('#messageBox ul').empty();
if (status){
var ids= $moGrid.jqGrid('getGridParam','selarrrow');
for (var i = 0; i < ids.length; i++)
{
var rowId = ids[i];
var rowData = $moGrid.jqGrid ('getRowData', rowId);
global_selectedGroupMRowData.push(rowData);
}
}else{
global_selectedGroupMRowIds.splice($.inArray(id, global_selectedGroupMRowIds), 1);
for(var i=0; i<global_selectedGroupMRowData.length; i++){
if (global_selectedGroupMRowData[i].id==id){
global_selectedGroupMRowData.splice(i, 1);
}
}
//global_selectedGroupMRowData.splice($.inArray($("#moTable").jqGrid('getRowData',id), global_selectedGroupMRowData), 1);
}
},
onSelectAll: function(aRowids, status) {
$('#messageBox ul').empty();
if (status){
for (var i = 0; i < aRowids.length; i++)
if ($.inArray(aRowids[i], global_selectedGroupMRowIds) == -1) {
global_selectedGroupMRowIds.push(aRowids[i]);
global_selectedGroupMRowData.push($("#moTable").jqGrid('getRowData',aRowids[i]));
}
} else {
for (var i = 0; i < aRowids.length; i++) {
global_selectedGroupMRowIds.splice($.inArray(aRowids[i], global_selectedGroupMRowIds), 1);
global_selectedGroupMRowData.splice($.inArray(aRowids[i], global_selectedGroupMRowData), 1);
}
}
},
loadComplete: function() {
var arraysize = global_selectedGroupMRowIds.length;
if (arraysize>0){
for (var i=0; i<arraysize; i++) {
$("#moTable").setSelection(global_selectedGroupMRowIds[i], false);
}
}
getEditPage('#moTable');
$("#moTable").find('#pager_left,#pager_center,#pager_right').hide();
}
});
It works to other pages that aren't modal. Just inside the modal it doesn't work.
Any idea?
I suppose that the problem can be fixed by changing the line
$this.jqGrid("setColWidth", iCol, colWidth + ($.jgrid.cell_width? cellLayout: 0));
so that colWidth will be increased to this.p.cellLayout (cellLayout parameter which equal to 5) if $.jgrid.cell_width is true:
$grid.on("jqGridAfterLoadComplete jqGridRemapColumns", function () {
var $this = $(this),
$cells = $this.find(">tbody>tr.jqgrow>td"),
$colHeaders = $($.map(this.grid.headers, function (item) { return item.el; })).find(">div"),
colModel = $this.jqGrid("getGridParam", "colModel"),
cellLayout = $this.jqGrid("getGridParam", "cellLayout"),
iCol,
iRow,
rows,
row,
n = $.isArray(colModel) ? colModel.length : 0,
cm,
colWidth,
idColHeadPrexif = "jqgh_" + this.id + "_";
$cells.wrapInner("<span class='mywrapping'></span>");
$colHeaders.wrapInner("<span class='mywrapping'></span>");
for (iCol = 0; iCol < n; iCol++) {
cm = colModel[iCol];
if (cm.hidden) {
continue;
}
colWidth = $("#" + idColHeadPrexif + $.jgrid.jqID(cm.name) + ">.mywrapping").outerWidth(true) + 25; // 25px for sorting icons
for (iRow = 0, rows = this.rows; iRow < rows.length; iRow++) {
row = rows[iRow];
if ($(row).hasClass("jqgrow")) {
colWidth = Math.max(colWidth, $(row.cells[iCol]).find(".mywrapping").outerWidth(true));
}
}
$this.jqGrid("setColWidth", iCol, colWidth + ($.jgrid.cell_width? cellLayout: 0));
}
});
The demo uses Bootstrap 3.2 and Font Awesome 4.2. Another demo uses the same code to autowidth of columns and it works too.
UPDATED: See one more demo.

Resources