Save values of dynamic generated HTML using javascript - javascript

I m generating dynamic html with its id. You can see the below link for the dynamic generated HTML.
Dymanic Generated HTML
So for saving this, I need some suggestion on how to save it in javascript. I tried the other fields of the HTML..
function SaveNPEDetails() {
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
// Need to write saving logic for dynamic generated html here.
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}

As per our discussion you can try something like
function SaveNPEDetails() {
var data = [];
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
var chs = $("#dvNPEAddData").children(".addNPEData")
for (var i = 0; i < chs.length; i++) {
var d = {};
var ch = chs[i];
var val = $(ch).find("input[name='TerRouteName']").val();
d[$(ch).find("input[name='TerRouteName']").attr("name")] = val;
val = $(ch).find("select[name='CableType']").val();
d[$(ch).find("select[name='CableType']").attr("name")] = val;
val = $(ch).find("select[name='CableSize']").val();
d[$(ch).find("select[name='CableSize']").attr("name")] = val;
val = $(ch).find("input[name='NoLiveFibre']").val();
d[$(ch).find("input[name='NoLiveFibre']").attr("name")] = val;
data.push(d);
}
var d = JSON.stringify(data);
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields , myJsonXML : d}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}

Using your example in the fiddle I've done the following
$('#submit').click(function() {
var DashboardFields = {},
status = true;
$.each($('input[type="text"]'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '') {
alert(id + ' field is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
$.each($('select'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '--Select--' || $(v).val() == null) {
alert(id + ' select is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
if(!status){
alert('you have empty fields');
} else {
console.log(DashboardFields); //Here should be your Ajax Call
}
});
JsFiddle
I've used your example with ID's and created a filter in order to take dynamically the fields not by ID's, I used the ID's to map the DashboardFields object but I strongly encourage to use name or other data- param and change the jQuery code after (the line with var id=$(v).attr('id'))
Hope this helps you

Related

Cannot access element in Javascript array

I'm trying to do Inventory checking with using ajax post method and return with some array value. My response is okay, but I cannot access the array value of my response. I'm using response[0] and response[1]["OptionKey"] but it doesn't show anything.
response
[6,{"OptionKey":"215,221,224"}]
javascript
function InventoryChecking(LineOptionData) {
var ItemID = $("#tiItemID").val();
var OptVal = LineOptionData;
$.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: '<?= site_url() ?>item/InventoryChecking',
data: "ItemID=" + ItemID + "&OptVal=" + OptVal + "&From=" + From,
success: function (response) {
console.log(response);
if (From === "mytray") {
$("#ItemBalance").text(response[0]);
} else {
$("#ItemBalance").text(response);
}
qty = $("#quantity").val();
if (From === "mytray" && response[0] - qty === -qty && BaseLineOptionData === response[1]["OptionKey"]) {
$("#btnAddToTray").attr("disabled", false);
} else if ((response - qty) < 0) {
// if( (response-qty)<0 ) {
if (response <= 0) {
$("#ItemBalance").text(0); //Show 0 instead of negative
}
if (ItemStockCheck == 0) {
$("#btnAddToTray").attr("disabled", true);
} else {
$("#btnAddToTray").attr("disabled", false);
}
} else {
$("#btnAddToTray").attr("disabled", false);
}
}
});
}
PHP to respond
if ($From === "mytray") {
$array = [$reserved,$CombineOptID];
echo json_encode($array);
}
Based on jwatts1980 comment, my response is in string. To fix this I need to change my response to Javascript object.
var obj = JSON.parse(response);

Why validation message is shown even after correcting values

I have html contact form in which i have handled validations in JS.
If there is any incorrect data/value in any field for e.g emailid, validation works correctly, but even after correcting the data it keeps popping.
Attaching the code and the screenshot for the same.
Please help.
function askfordemo() {
var path = document.URL;
var url = "";
url = new URL(path);
var frm = $(document.forms);
var formData = JSON.stringify(frm.serialize());
var name = $("#name").val();
var emailID = $("#emailID").val();
var phone = $("#phone").val();
var companyname = $("#companyname").val();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(emailID)) {
return true;
} else {
$("#emailID")[0].setCustomValidity('Invalid Email Address');
return false;
}
if ($('#date1') != null && $('#date1').is(':visible')) {
var contactdate = new Date($('#date1').val());
var dateNow = new Date();
var msg = "Date cannot be less than todays date";
if (contactdate < dateNow) {
$("#date1")[0].setCustomValidity('Date cannot be less than todays date');
return;
} else if (contactdate == 'Invalid Date') {
$("#date1")[0].setCustomValidity('Please fill out this field with Date and Time');
return
} else {
$("#date1")[0].setCustomValidity("");
}
}
if (name === '' || emailID === '' || phone === '' || companyname === '' || noofemployees === null || message === '' ||
radioValue === '' || (typeof radioValue === 'undefined')) {
return false;
}
var param = new Object();
param.name = encodeURIComponent(name);
param.emailID = encodeURIComponent(emailID);
param.phone = encodeURIComponent(phone);
param.companyname = encodeURIComponent(companyname);
param.noofemployees = encodeURIComponent(noofemployees);
param.message = encodeURIComponent(message);
param.radioValue = encodeURIComponent(radioValue);
param.date1 = encodeURIComponent(date1);
param.timezone = encodeURIComponent(timezone);
var paramjson = JSON.stringify(param);
path = path.substring(0, path.lastIndexOf("/"));
$.ajax({
url: path + '/ms/askForDemo/sendMail',
type: 'POST',
data: paramjson,
dataType: "json",
contentType: "application/json",
crossDomain: 'true',
success: function(formData) {
JSON.stringify(formData)
},
error: function(x, y, z) {
alert("Internet connection is lost. Please try again later.");
}
});
}

how to push values to an array outside the loop from a nested ajax call with javascript

I have a for loop which loops about 16 times and each time it loops i want a value to be pushed to the array i declared outside the loop and the array is pushed from a nested ajax call in the loop. i wrote an if condition that if the loop reaches 16 times it should alert all the contents of the array at once but i'm getting an empty value
var comment = [];
for (var i = 0; i < jsons.length; i++){
var obj = jsons[i];
if( i == jsons.length - 1 )
{
alert(comment);
break;
}
var idno = '';
idno = obj.IDNO;
var amount = obj.AMOUNT;
(function(i)
{
$.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoauth: obj.IDNO, amount: amount, },
dataType: 'json',
cache: false,
success: function(result){
if(result[0].idno == '')
{
alert(result[0].idno + " " + result[0].amount);
}
else if(result[0].idno != ''){
var idnoresult = result[0].idno;
var amountresult = result[0].amount;
$.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoinsert: idnoresult, amountinsert: amountresult},
cache: false,
success: function(gg){
if(gg != '')
{
comment[i] = gg;
}
}
});
}
}
});
})(i);
}
the updated one is still not working as expected its returning an empty array
var comment = [];
for (var i = 0; i < jsons.length; i++){
//var comments = [];
var obj = jsons[i];
/*if (typeof obj.IDNO === 'string' && obj.IDNO.length)
{
alert('good');
}
else{
alert('bad');
}*/
//alert(obj.REASON);
//console.log(obj);
//alert(obj.REASON);
if( i == jsons.length - 1 )
{
alert(comment);
break;
}
var idno = '';
idno = obj.IDNO;
var amount = obj.AMOUNT;
var jqxhr1 = $.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoauth: obj.IDNO, amount: amount, },
dataType: 'json',
});
var jqxhr2 = $.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoinsert: obj.IDNO, amountinsert: amount},
});
$.when(jqxhr1, jqxhr2).then(function(result, gg) {
//alert(result[0].idno + " " + result[0].amount);
if(result[0].idno == ''/*&& result[0].amount == '' && result[0].idnoerror != ''*/)
{
alert(result[0].idno + " " + result[0].amount);
comments.push(result);
}
else if(result[0].idno != ''/* && result[0].amount != '' && result[0].idnoerror == ''*/){
var idnoresult = result[0].idno;
var amountresult = result[0].amount;
if(gg != '')
{
comment.push(gg);
/*if( i == jsons.length - 1 )
{*/
//alert(gg);
//alert(comments);
//break;
//}
}
}
//alert(idnoresult + " " + amountresult);
// Handle both XHR objects
//alert("all complete");
});
//})(i);
}enter code here

Iterate over array items and check property value

function GetViewModelData() {
var RDcViewModel = [];
var recordId = $.trim($("#recordId").val());
for (i = 1; i <= rowCount; i++) {
var item1 = $.trim($("#item1" + i).val()) == '' ? 0 : parseInt($("#item1" + i).val());
var item2 = $.trim($("#item2" + i).val()) == '' ? 0 : parseInt($("#item2" + i).val());
var GrandTotal = (item1 + item2);
var rdtCViewModel = new ItemDetailsViewModel(0, item1, item2, GrandTotal);
RDcViewModel.push(rdtCViewModel);
}
var obj = new ReportViewModel(recordId, RDcViewModel);
var viewmodel = JSON.stringify(obj);
return viewmodel;
}
I have the above sample function that i'm using to iterate over html table rows and storing the row values in an array.
Once i have my array populated, i'm using below code snippet to post the data to my controller.
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
//i want to check from here if viewmodel has any item(row) where GrandTotal is 0 (zero)
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function (data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function (e) {
return false;
}
});
});
}
What i now want to do in my PostData function is to check if my "viewmodel" object contains any item(row) where "GrandTotal" is 0.
using JSON.parse(viewmodel), prepare object of type ReportViewModel with RDcViewModel JS array of type ItemDetailsViewModel and iterate over it to find if any grandtotal == 0 for ItemDetailsViewModel instances
var viewmodel = GetViewModelData(),
var obj = JSON.parse(viewmodel);
var bFoundZero=false;
$.each(obj.RDcViewModelArray, function(idx, elem){
if( elem.GrandTotal === 0 ) bFoundZero=true;
})
if( bFoundZero ) return 0;
As you have stringified it, now you have to parse it back if you want to access its keys and values:
var PostData = function() {
$(".btnSubmit").click(function() {
var viewmodel = GetViewModelData(),
viewObj = JSON.parse(viewmodel),
flag = false; // <-----parse it back here
viewObj.forEach(function(i, el){
flag = el.GrandTotal === 0;
return flag;
});
if(flag){ return false; } // <------ and stop it here.
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function(data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function(e) {
return false;
}
});
});
}
There is no point iterating array again. Break the loop in GetViewModelData() and return false from that function. Then test it in PostData
Inside existing for loop:
var GrandTotal = (item1 + item2);
if(!GrandTotal){
return false;
}
Then in PostData()
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
if(viewmodel === false){
alert('Missing total');
return; //don't proceed
}
/* your ajax */

Java Script if statement not working

I have javascript function that includes few if else statements for some reason one of the statements is not working properly.
Script:
function makePayment(reservationID) {
var expirationDate = $("#expirationDate").val();
var creditCard = $("#creditcard").val();
if (creditCard.length == 16 && expirationDate.length == 4) {
var month = "";
var year = "";
month += expirationDate.charAt(0);
month += expirationDate.charAt(1);
year += expirationDate.charAt(2);
year += expirationDate.charAt(3);
var monthInt = parseFloat(month);
var yearInt = parseFloat(year);
var currect;
if (monthInt > 0 && monthInt < 13 && yearInt > 12 && yearInt < 24) {
$.ajax({
url: "CreditAuthentication",
data: "type=reserve&creditCard=" + creditCard + "&expirationDate=" + expirationDate,
success: function(responseText) {
currect = responseText;
console.log(responseText);
}, error: function(xhr) {
alert(xhr.status);
}});
if (currect == true) {
//
$.ajax({
type: "POST",
url: "paymentMethods",
data: "type=make&reservationID=" + reservationID,
success: function(msg) {
console.log("Paymentmade");
alert("Payment made");
//alert(CCA);
document.location = "index.jsp#reservation";
}
});
}
else if(currect === "false") {
alert("Please enter valid details. 3rd");
}
//
} else {
alert("Please enter valid details. 2nd");
}
} else {
alert("Please enter valid payment information. 1st");
}
}
I have checked in FireBug and the return value from my servlet is correct and and the console.log(responseText); displays the response in console. However for some reason this part of statement is not working and not displaying the alerts:
if (currect == true) {
$.ajax({
type: "POST",
url: "paymentMethods",
data: "type=make&reservationID=" + reservationID,
success: function (msg) {
console.log("Paymentmade");
alert("Payment made");
document.location = "index.jsp#reservation";
}
});
} else if (currect === "false") {
alert("Please enter valid details. 3rd");
}
Thanks in Advance!
Please make sure currect is not null or undefined and if it is not.
make a 'currect' global so it can be accessable:
var currect; //declare it here
$.ajax({
url: "CreditAuthentication",
data: "type=reserve&creditCard=" + creditCard + "&expirationDate=" + expirationDate,
success: function(responseText) {
currect = responseText;
console.log(responseText);
}, error: function(xhr) {
alert(xhr.status);
}});
then if currect is a boolean then try:
if (currect) {
//your code
} else {
//your code
}
and if it is string:
if (currect === 'true') {
//your code
} else if(currect === 'false') {
//your code
}
You have to place the currect if/else in the success function of your ajax call.

Categories

Resources