Call every element one by one - javascript

I have 3 paragraphs here. The problem is that they are displaying at the same time.
What I wanted is they will auto show and then hide one at a time.
Scenario:
First paragraph // show then hide
Sec paragraph // next show then hide
Third paragraph // next show then hide
if(p_name != "" && l_name != "" && t_name !="")
{
session.rpc('/custom/custom',
{
p_name: p_name,
}).then(function ()
{
$("p.one").addClass("show").hide(5000);
});
session.rpc('/cus/cus',
{
l_name : l_name,
}).then(function ()
{
$("p.two").addClass("show").hide(5000);
});
session.rpc('/cuz/cuz',
{
t_name : t_name,
}).then(function ()
{
$("p.three").addClass("show").hide(5000);
});
}

maybe this is what you are looking for
if (p_name != "" && l_name != "" && t_name != "") {
session.rpc('/custom/custom', {
p_name: p_name,
}).then(function() {
$("p.one").addClass("show").hide(5000);
session.rpc('/cus/cus', {
l_name: l_name,
}).then(function() {
$("p.two").addClass("show").hide(5000);
session.rpc('/cuz/cuz', {
t_name: t_name,
}).then(function() {
$("p.three").addClass("show").hide(5000);
});
});
});
}

Related

Wait for Sweet Alert input if a condition is met, otherwise continue

I have this script, which in some cases may require user input. It works, but the script continues regardless of the result of the Sweet Alert input.
$('#cart').on('click', '.button', function() {
var code = $(this).data('code')
if ((code !== '') && (code !== null) && (code !== undefined)) {
var repeated = 0
var secondary = null
if (code.startsWith('ABC')) {
swalBs.fire({
text: 'Enter secondary code',
showCancelButton: true,
cancelButtonText: 'Cancel',
showConfirmButton: true,
confirmButtonText: 'Confirm',
reverseButtons: true,
input: 'text',
inputValidator: (value) => {
if (!value) {
return 'Code required'
}
}
})
.then((result) => {
console.log(result)
secondary = result.value
})
}
if (repeated < 1) {
$.post(serviceUrl, {
c : code,
s : secondary
}, function(response) {
...
})
.fail(function() {
...
})
} else {
swalBs.fire('Error', 'Code already entered', 'error')
}
} else {
swalBs.fire('Enter code', 'Field must not be blank.')
}
})
How can I make this script wait for the Sweet Alert input while still allowing the $.post to happen when the if (code.startsWith('ABC')) condition is not met (and Sweet Alert is not needed)?

Kendo Grid Binding with Razor

I setup a function used to save the grid's state along with its options to a database whenever something is modified. Every user will have their own respective settings.
The saving and loading functions of the grip options are functional, however upon page loading, the loadGridState function is called and so is the saveGridState although no change has been made to the grid by the user yet.
I would like to learn about a better way to perform the binding with the grid upon loading without having to mix the save functions with the databound event functions from Kendo.
This is the code within a JavaScript section:
$(function () {
$("#navHistory").addClass("navMenuSelected");
$("#navHistory > a").css("color", "black");
var grid = $("#HistoricGrid").data("kendoGrid");
var gridstate = kendo.stringify(grid.getOptions());
grid.bind("dataBound", onDataBound);
grid.bind("columnResize", onColumnResize);
LoadGridState();
$('#search').click(function (e) {
e.preventDefault();
$('#excelButton').prop('disabled', true);
$('#pdfButton').prop('disabled', true);
$('search').prop('disabled', true);
grid.dataSource.read();
});
$('#excelButton').click(function () {
grid.saveAsExcel();
});
$('#pdfButton').click(function () {
grid.saveAsPDF();
});
$("#save").click(function (e) {
e.preventDefault();
SaveGridState();
});
$("#load").click(function (e) {
e.preventDefault();
LoadGridState();
});
//Grid event.
function onDataBound(e) {
SaveGridState();
var excelActivation = $('#excelButton').prop('disabled');
var pdfActivation = $('#pdfButton').prop('disabled');
var searchActivation = $('#search').prop('disabled');
if (excelActivation) {
$('#excelButton').prop('disabled', false);
}
if (pdfActivation) {
$('#pdfButton').prop('disabled', false);
}
if (searchActivation) {
$('#search').prop('disabled', false);
}
}
//Grid event.
function onColumnResize(e) {
SaveGridState();
}
function SaveGridState() {
//region #Bug 1818 - New SaveGridState() function saves the Grid's State independent of the language
var gridOptions = grid.getOptions();
if (gridOptions != null &&
gridOptions.dataSource &&
gridOptions.dataSource.transport != null &&
gridOptions.dataSource.transport.read &&
gridOptions.dataSource.transport.read.url != null
) {
delete gridOptions.dataSource.transport.read.url;
}
if (gridOptions != null &&
gridOptions.groupable &&
gridOptions.groupable.messages != null &&
gridOptions.groupable.messages.empty &&
gridOptions.groupable.messages.empty != null
) {
delete gridOptions.groupable.messages.empty;
}
if (gridOptions != null &&
gridOptions.pageable &&
gridOptions.pageable.messages != null &&
gridOptions.pageable.messages.itemsPerPage &&
gridOptions.pageable.messages.itemsPerPage != null
) {
delete gridOptions.pageable.messages.itemsPerPage;
}
$(gridOptions.columns).each(function () {
$(this).removeProp("title");
});
var gridColumns = kendo.stringify(gridOptions);
console.log(gridOptions);
$.ajax({
url: '#Url.Action("GridSaveOption", "Global")',
type: 'POST',
async: false,
data: { gridName: "HistoricGrid", gridOption: gridColumns },
success: function (result, status) { },
error: function (result, status) {
console.log('Error on SaveGrid.');
}
});
//end region #Bug 1818
}
function LoadGridState() {
$.ajax({
url: '#Url.Action("GridLoadOption", "Global")',
type: 'POST',
async: false,
data: { gridName: "HistoricGrid" },
datatype: 'text',
success: function (result, status) {
//region #Bug 1822 - Adjust the titles of the Grid to the current language
//If there is a corresponding data grid option for current user
if (result) {
var gridOptions = JSON.parse(result);
if (gridOptions != null &&
gridOptions.dataSource &&
gridOptions.dataSource.transport != null &&
gridOptions.dataSource.transport.read &&
gridOptions.dataSource.transport.read.url != null
) {
delete gridOptions.dataSource.transport.read.url;
}
if (gridOptions != null &&
gridOptions.groupable &&
gridOptions.groupable.messages != null &&
gridOptions.groupable.messages.empty &&
gridOptions.groupable.messages.empty != null
) {
delete gridOptions.groupable.messages.empty;
}
if (gridOptions != null &&
gridOptions.pageable &&
gridOptions.pageable.messages != null &&
gridOptions.pageable.messages.itemsPerPage &&
gridOptions.pageable.messages.itemsPerPage != null
) {
delete gridOptions.pageable.messages.itemsPerPage;
}
if (gridOptions != null &&
gridOptions.pdf
) {
delete gridOptions.pdf;
}
if (gridOptions != null &&
gridOptions.columns
) {
delete gridOptions.columns;
}
grid.setOptions(gridOptions);
//end region #Bug 1822
}
//If there is no data grid option for current user, use default
else {
//#Bug 1866 - In case the user has no style defined, it will order by creation date by default
var dsSort = [];
dsSort.push({ field: "CreationDate", dir: "desc" });
grid.dataSource.sort(dsSort);
}
},
error: function (result, status) {
console.log('Error on LoadGrid.');
}
});
}
});

Error with Knockout-validation validation

I have a collection of text editors in a form, validating them with knockout-validation. When I submit the form, only a few of them show validation errors, although all of them should pass. This issue only occurs with these two fields shown in error, however I have checked and double checked and all of the wiring for all of these is set up correctly, e.g. there is no reason I can see that these two fields should be different from the others that do not exhibit this issue.
I'm hoping that someone with more experience than I in the internals of knockout-validation could point me to something that may be alternately tripping the validation of these. I have it set up to validate the text when a user clicks outside of the editor, and that works fine. The issue below only appears when a user clicks submit, and other fields on the page (besides the editors shown here) have an issue. In other words, if every single field is valid, the form is submitted. If any fields OTHER than those shown below have issues, the false positive is shown.
Adding Code examples:
Creating the validator and extending the observables. Note the ones depicted in the image are configured identically to those not being marked invalid:
ko.validation.rules['notIn'] = {
validator: function (value, params) {
var thisValidator = baseCompare.slice();
if (Array.isArray(params))
params.forEach(function (element, index, array) {
thisValidator.push(element);
});
else
thisValidator.push(params);
return thisValidator.indexOf(value) == -1;
},
message: 'Please enter a unique value'
};
ko.validation.registerExtenders();
self.setupValidation = function () {
self.title.extend({
required: true,
notIn: {
message: 'Please enter a unique title',
params: self.froalaBasify('New Change Request')
}
});
self.domain.extend({ required: true, notEqual: '0' }).extend({ notify: 'always' });
self.priority.extend({ required: true, notEqual: '0' }).extend({ notify: 'always' });
self.securityClassification.extend({ required: true, notEqual: '0' }).extend({ notify: 'always' });
self.impact.extend({ required: true, notEqual: '0' }).extend({ notify: 'always' });
self.customersAffected.extend({
required: true,
notIn: {
message: 'Please describe the customers affected',
params: self.froalaBasify(CRHelper.ValidationPlaceholders.customersAffected)
}
});
//False Positive
self.justification.extend({
required: true,
notIn: {
message: 'Please provide a justification for the request',
params: self.froalaBasify(CRHelper.ValidationPlaceholders.justification)
}
});
self.scope.extend({
required: true,
notIn: {
message: 'Please describe the systems affected by this change',
params: self.froalaBasify(CRHelper.ValidationPlaceholders.scope)
}
});
//False Positive
self.validationProcess.extend({
required: true,
notIn: {
message: 'Please enter a validation plan for this change',
params: self.froalaBasify(CRHelper.ValidationPlaceholders.validationProcess)
}
});
self.description.extend({
required: true,
notIn: {
message: 'Please enter a description',
params: self.froalaBasify(CRHelper.ValidationPlaceholders.description)
}
});
self.deadlineRequested.extend({
required: true,
dateGreaterThanToday: {
onlyIf: function () {
//var isTrue = $('#ddTransition option:selected').text() == "Delete Request";
//return !(isTrue);
return self.id === 0;
}
}
});
//self.deadlineRequested.extend({
// required: true}).extend({ notify: 'always' });
};
And then here is the submit handler:
self.submitChangeRequest = function () {
var validated = ko.validatedObservable(self.ChangeRequest());
var transition = "";
transition = $('#ddTransition option:selected').text();
var disableValidation = false;
if (transition == "Delete Request")
disableValidation = true;
var formIsValid = validated.isValid();
if (CRHelper.ConfirmSubmitIfDeleteChosen() && (disableValidation || formIsValid)) {
$('.submitter').prop('disabled', true);
var formUsage = $("[id*='hdnFormUsage']")[0].value;
var ajax = new utils.AjaxFormatter(
{
type: "POST",
data: ko.toJSON(self.ChangeRequest()),
url: DomainUtil.baseUrl + "api/ChangeRequests/",
contentType: "application/json",
headers: { 'formUsage': formUsage }
},
function (updatedModel, status, request) {
var updateMessage = formUsage == 'execute' ? 'executed' : (formUsage == 'new' ? 'saved new' : transition == 'Delete Request' ? 'deleted' : 'updated');
var $msg = $("[id*='StatusMessage']");
$msg.html('Successfully ' + updateMessage + ' Change Request ' + updatedModel.id);
$msg.addClass('alertGo').show().fadeOut({ duration: 8000, easing: 'easeInQuint', complete: function () { $msg.removeClass('alertGo'); } });
if (formUsage == 'new') {
changeRequestViewModel.SetChangeRequest(new ChangeRequestModel());
CRHelper.SetEditors('new');
} else {
changeRequestViewModel.SetChangeRequest(new ChangeRequestModel(updatedModel));
CRHelper.SetEditors('edit');
}
if ((formUsage == 'editState' || formUsage == 'edit') && updatedModel.activeStateId === 8)
$('#approvedByItems').toggle();
if (formUsage === 'execute' || (formUsage === 'editState' && updatedModel.activeStateName == 'Approved')) {
$('#divExecuted').toggle();
$('#divChangeState').hide();
}
try {
$('#dtpDeadlineRequested').datepicker();
$('#dtpDeadlineRequested').datepicker('refresh');
} catch (e) {
$('#dtpDeadlineRequested').datepicker('destroy');
$('#dtpDeadlineRequested').datepicker();
}
if (transition == "Delete Request") {
$('.submitter').prop('disabled', true);
$('#divSubmitButtons #buttonSet').toggle();
$('#divSubmitButtons #returnLink').toggle();
$('#formFields').prop('disabled', true);
}
if (updatedModel.activeStateName == 'Executed' || updatedModel.activeStateName == 'Deleted' || updatedModel.activeStateName == 'Approved') {
$('#formFields').prop('disabled', true);
$('.editor').unbind('dblclick');
$('#divSubmitButtons #buttonSet').toggle();
$('#divSubmitButtons #returnLink').toggle();
}
},
function (request, status, error) {
//update message text
var $msg = $("[id*='StatusMessage']");
var updateMessage = formUsage == 'execute' ? 'executing' : (formUsage == 'new' ? 'saving' : 'updating');
$msg.html('Failure ' + updateMessage + ': ' + error);
$msg.addClass('alertStop').show().fadeOut({ duration: 8000, easing: 'easeInQuint', complete: function () { $msg.removeClass('alertStop'); } });
},
function () {
if (pwChooser)
pwChooser.selectedPW([]);
//hide spinny
}
);
utils.tokenizedAjax(ajax);
} else {
ko.validation.group(self.ChangeRequest()).showAllMessages();
var $msg = $("[id*='StatusMessage']");
$msg.html('Check your entries and try again')
.addClass('alertCaution')
.show()
.fadeOut({
duration: 2000,
easing: 'easeInQuint',
complete: function () {
$msg.removeClass('alertCaution');
}
});
}
}
And then here is where I declare the observables on the model - all pretty straightforward:
self.description = ko.observable(crData.description || '');
self.domain = ko.observable(crData.domain || '');
self.id = crData.id || 0;
self.impact = ko.observable(crData.impact || '');
self.includesPolicyWaiver = ko.observable(crData.includesPolicyWaiver || false);
self.justification = ko.observable(crData.justification || '');
self.priority = ko.observable(crData.priority || '');
self.scope = ko.observable(crData.scope || '');
self.securityClassification = ko.observable(crData.securityClassification || '');
self.title = ko.observable(crData.title || 'New Change Request');
self.validationProcess = ko.observable(crData.validationProcess || '');
I've triple-checked the code and there is nowhere else that the values behind these two form fields are being explicitly changed. This looks to me like a global-type value is getting toggled then not reset or something.
This is interesting: The only change I made was the order of the elements in the html. Doing the same test/submission, now the other fields that are in the 2nd and 4th position are showing the false positive. The ones that showed it originally validate as expected.

kendo grid inline edit dropdown will not expand on tab navigation

I'm having an issue with Kendo Grid in Angular where the custom drop down I've implemented will not open when tab navigating to that column. The built in text and number editor fields are editable on tab navigation but my custom drop down will not expand. I have to click on it to get the drop down effect.
My goal here is to allow the user to log an an entire row of data without having to take their hands off the keyboard.
My column is defined like so:
gridColumns.push({
field: currentField.FieldName.replace(/ /g, "_"),
title: currentField.FieldName,
editor: $scope.dropDownAttEditor,
template: function (dataItem) {
return $scope.dropDownTemplate(dataItem, currentField.FieldName);
}
});
My gridOptions are defined as follows:
$scope.gridOptions = {
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: appconfig.basePath + '/api/DrillHoleManager/DrillHoleInterval',
type: 'POST',
contentType: 'application/json'
},
update: {
url: appconfig.basePath + '/api/DrillHoleManager/DrillHoleIntervalUpdate',
type: 'POST',
contentType: 'application/json'
},
parameterMap: function (data, operation) {
if (operation === "read") {
data.DrillHoleId = $scope.entity.Id;
data.DrillHoleIntervalTypeId = $stateParams.ddhinttypeid;
// convert the parameters to a json object
return kendo.stringify(data);
}
if (operation === 'update') {
// build DrillHoleIntervalDto object with all ATT/CMT values to send back to server
var drillHoleInterval = { Id: data.Id, Name: data.Name, From: data.From, To: data.To };
drillHoleInterval.Attributes = [];
drillHoleInterval.Comments = [];
var attributeFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalAttribute });
$.each(attributeFields, function (idx, attributeField) {
drillHoleInterval.Attributes.push({
Id: attributeField.AttributeDto.Id,
LookupId: data[attributeField.FieldName.replace(/ /g, "_")]
});
});
var commentFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalComment });
$.each(commentFields, function (idx, commentField) {
drillHoleInterval.Comments.push({
Id: commentField.CommentDto.Id,
Value: ((data[commentField.FieldName.replace(/ /g, "_")] != "") ? data[commentField.FieldName.replace(/ /g, "_")] : null)
});
});
return kendo.stringify(drillHoleInterval);
}
// ALWAYS return options
return options;
}
},
schema: { model: { id : "Id" }},
serverPaging: false,
serverSorting: false,
serverFiltering: false
//,autoSync: true
}),
columns: gridColumns,
dataBound: onDataBound,
autoBind: false,
navigatable: true,
scrollable: false,
editable: true,
selectable: true,
edit: function (e) {
var grid = $("#ddhintgrid").data("kendoGrid");
//grid.clearSelection();
grid.select().removeClass('k-state-selected');
// select the row currently being edited
$('[data-uid=' + e.model.uid + ']').addClass('k-state-selected');
e.container[0].focus();
}
};
Here is a custom event to handle the 'Tab' keypress. The point of this is I want a new record automatically added to the grid if the user presses 'Tab' at the end of the last line:
$("#ddhintgrid").keydown(function (e) {
if (e.key == "Tab") {
var grid = $("#ddhintgrid").data("kendoGrid");
var data = grid.dataSource.data();
var selectedItem = grid.dataItem(grid.select());
var selectedIndex = null
if (selectedItem != null) {
selectedIndex = grid.select()[0].sectionRowIndex;
if (selectedIndex == data.length - 1) { // if the bottom record is selected
// We need to manually add a new record here so that the new row will automatically gain focus.
// Using $scope.addRecord() here will add the new row but cause the grid to lose focus.
var newRecord = { From: grid.dataSource.data()[selectedIndex].To };
var currentCmtFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalComment; });
$.each(currentCmtFields, function (idx, currentCmtField) {
newRecord[currentCmtField.FieldName.replace(/ /g, "_")] = null;
});
grid.dataSource.insert(data.length, newRecord);
// edit the new row
grid.editRow($("#ddhintgrid tr:eq(" + (data.length) + ")"));
}
}
}
});
Here is my template for the drop down column:
$scope.dropDownTemplate = function (dataItem, fieldName) {
var currentLookups = $.grep($scope.currentFields, function (e) { return e.FieldName == fieldName; })[0].AttributeDto.Lookups;
var selectedLookup = $.grep(currentLookups, function (e) { return e.Id == dataItem[fieldName.replace(/ /g, "_")]; })[0];
// With the custom dropdown editor when going from null to a value the entire lookup object (id, name) is placed in the
// dataItem[field_name] instead of just the id. We need to replace this object with just the id value and return the name of
// the lookup to the template.
if (typeof selectedLookup == 'undefined' && dataItem[fieldName.replace(/ /g, "_")] != null) {
selectedLookup = angular.copy(dataItem[fieldName.replace(/ /g, "_")]);
dataItem[fieldName.replace(/ /g, "_")] = selectedLookup.Id;
}
if (selectedLookup != null && selectedLookup != '') {
return selectedLookup.Name;
}
else {
return '';
}
};
And finally here is the custom editor for the drop down column:
$scope.dropDownAttEditor = function (container, options) {
var editor = $('<input k-data-text-field="\'Name\'" k-data-value-field="\'Id\'" k-data-source="ddlDataSource" data-bind="value:' + options.field + '"/>')
.appendTo(container).kendoDropDownList({
dataSource: $.grep($scope.currentFields, function (e) { return e.FieldName == options.field.replace(/_/g, ' '); })[0].AttributeDto.Lookups,
dataTextField: "Name",
dataValueField: "Id"
});
};
I know this is a lot to take in but if you have any questions just let me know.
My ultimate goal is that I want the user to be able to navigate the grid using the 'Tab' key and edit every field without having to use the mouse.

JQuery popup $.post inner function do not working

Please help me in my Javascript - $.post - popup script. I tried to debug the script below, but I found that it doesn't go inside the function(data)... What can be the problem? Thanks for replies.
Here is my code:
$(function () {
$('#survey').dialog({
bgiframe: true,
autoOpen: false,
modal: true,
width: 500,
resizable: false,
buttons: {
Submit: function () {
if ($("input[name='elso']:checked").val() !== undefined && $("input[name='masodik']:checked").val() !== undefined && $("input[name='harmadik']:checked").val() !== undefined && $("input[name='negyedik']:checked").val() !== undefined) {
setCookie('POPsurvey', 'POPsurvey', 30);
$.post("process_survey.php", $("#popup_survey").serialize(), alert("hsgh"),
function (data) {
if (data.db_check == 'fail') {
$("#error_message").html("<p>Adatbázisunk nem elérhető. Kérjük, próbálja meg újra.</p>");
} else {
$('#survey').dialog('close');
$('#survey_thanks').dialog('open');
}
}, "json");
} else {
$("#error_message").html("<p>Kérjük, minden kérdésre adjon választ.</p>");
}
}
}
});
});
You can do it this way
$.post("process_survey.php", $("#popup_survey").serialize()).done( function (data) {
if (data.db_check == 'fail') {
$("#error_message").html("<p>Adatbázisunk nem elérhető. Kérjük, próbálja meg újra.</p>");
} else {
$('#survey').dialog('close');
$('#survey_thanks').dialog('open');
}
});
$(function () {
$('#survey').dialog({
bgiframe: true,
autoOpen: false,
modal: true,
width: 500,
resizable: false,
buttons: {
Submit: function () {
if ($("input[name='elso']:checked").val() !== undefined && $("input[name='masodik']:checked").val() !== undefined && $("input[name='harmadik']:checked").val() !== undefined && $("input[name='negyedik']:checked").val() !== undefined) {
setCookie('POPsurvey', 'POPsurvey', 30);
$.post("process_survey.php", $("#popup_survey").serialize(),
function (data) {
if (data.db_check == 'fail') {
$("#error_message").html("<p>Adatbázisunk nem elérhető. Kérjük, próbálja meg újra.</p>");
} else {
$('#survey').dialog('close');
$('#survey_thanks').dialog('open');
}
}, "json");
} else {
$("#error_message").html("<p>Kérjük, minden kérdésre adjon választ.</p>");
}
}
}
});
});
function (data) must be after serialize
Please remove that alert as the third parameter in the post function like this
$.post("process_survey.php", $("#popup_survey").serialize(),
function (data) {
if (data.db_check == 'fail') {
$("#error_message").html("<p>Adatbázisunk nem elérhető. Kérjük, próbálja meg újra.</p>");
} else {
$('#survey').dialog('close');
$('#survey_thanks').dialog('open');
}
}, "json");
The problem is in your serialize
add this to your code and use serializeObject (not serialize)
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

Categories

Resources