I would like to use the same alert message to display all the messages at once.
function LoadData(obj) {
var ArrayData = $('input[type="hidden"][id^="li"]').map(function() {
return this.getAttribute("value");
}).get();
$.ajax({
data: {
GUID: JSON.stringify(ArrayData)
},
url: "/LoadOrder/LoadData",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(result) {
if (result.length > 0) {
for (var item of result) {
alert("There are problems with your selections ${item.Desc} and ${item.EDesc}
.");
}
}
}
});
}
Expected result should be displayed like below only once.
Currently, the same message displays 3 times.
`There are problems with your selections.
ABC - CDE
GFE- Test
Test1 - Test2`
Is there any way to display all in once.
CodePudding user response:
Yes, you can display all the messages in one alert by concatenating the messages and creating a single string. Here's the updated code:
var ArrayData = $('input[type="hidden"][id^="li"]').map(function() {
return this.getAttribute("value");
}).get();
$.ajax({
data: {
GUID: JSON.stringify(ArrayData)
},
url: "/LoadOrder/LoadData",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(result) {
if (result.length > 0) {
var message = "There are problems with your selections: \n";
for (var item of result) {
message = item.Desc " - " item.EDesc "\n";
}
alert(message);
}
}
});
}
This way, the final message will contain all the information in one string and will be displayed in a single alert.
CodePudding user response:
You could change the success
callback so that you first create the list of messages as a string and then call the alert
success: function(result) {
if (result.length > 0) {
const problems = result.map(item => `${item.Desc} - ${item.EDesc}`).join('\n');
alert(`There are problems with your selections.\n${problems}`);
}
}
and without using arrow functions
success: function(result) {
if (result.length > 0) {
var problems = result.map(function(item) {
return `${item.Desc} - ${item.EDesc}`
}).join('\n');
alert(`There are problems with your selections.\n${problems}`);
}
}