Disable/Enable HTML Button based on Existing Functions - javascript

I have a function running onclick from HTML button and need to add disabling the button on success but NOT on return = false.
I've tried toggling, disabling directly in the HTML and inserting changing the HTML attribute within my current function.
var amtCount = 0;
function addToLineItem()
{
var totalAmount = 0.0;
var valid = true;
var difference = [];
$.each($(".tbodys tr"),function(index,vs)
{
for(var tdcnt = 0; tdcnt < vs.children.length - 1; tdcnt++)
{
if(tdcnt != 5)
if(vs.children[tdcnt].firstElementChild.value == "" || vs.children[tdcnt].firstElementChild.value == undefined)
valid = false;
}
if(vs.children[9].firstChild.value != "" && vs.children[9].firstChild.value != undefined)
{
RMID.push(vs.children[9].firstChild.value);
}
});
if(CodingListItem.length > 0)
{
difference = arr_diff(CodingListItem,RMID);
}
if(valid == false)
{
alert("Message");
return false;
}
if($("#aprDate").val() == "")
{
alert("Please date.");
return false;
}
$.each($(".tbodys tr .nine"),function(index,vs){
totalAmount += parseFloat(vs.firstElementChild.value.replace(/,/g, ""));
});
if($("#Total")[0].innerText == "")
{
alert("Please .");
return false;
}
//if(parseFloat($("#invTotal").val().replace(/,/g, "")) != totalAmount)
if(parseFloat($("#invTotal").val().replace(/,/g, "")) != parseFloat($("#Total")[0].innerText.replace(/,/g, "")))
{
alert("total amount does not match.");
return false;
}
SP.SOD.executeFunc("sp.js", 'SP.ClientContext', function()
{
try
{
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var oList = clientContext.get_web().get_lists().getByTitle('Invoice');
if(difference.length > 0)
{
$.each(difference, function( index, value )
{
deleteListItem(parseInt(value));
});
}
$.each($(".tbodys tr"),function(i,v)
{
if(v.children[9].firstChild.value != "" && v.children[9].firstChild.value != undefined)
{
var itemType1 = GetItemTypeForListName("InvoiceLineItem");
var item1 = {
"__metadata": { "type": itemType1 },
"Title": v.children[0].firstChild.value,
"InvoiceIDId": parseInt(INV),
"Entity": v.children[1].firstChild.value,
"MS": v.children[2].firstChild.value,
"LocationId": parseInt(v.children[3].firstChild.value),
"DepartmentId": parseInt(v.children[4].firstChild.value),
"Account": v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text,
"SubAccount": v.children[6].firstChild.value,
"GLCode": v.children[7].firstChild.value,
"Amount": v.children[8].firstChild.value
};
updateListItem(parseInt(v.children[9].firstChild.value), "Invoice Approval and Coding", _spPageContextInfo.webAbsoluteUrl, item1, function () {
amtCount = amtCount + 1;
updatePendingInvoice(amtCount);
}, function () { errorMsg = true; });
}
else
{
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', v.children[0].firstChild.value); //Line Description
oListItem.set_item('InvoiceID', INV);
oListItem.set_item('Entity', v.children[1].firstChild.value);
oListItem.set_item('MS', v.children[2].firstChild.value);
oListItem.set_item('Location', v.children[3].firstChild.value);
oListItem.set_item('Department', v.children[4].firstChild.value);
oListItem.set_item('Account', v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text);
oListItem.set_item('SubAccount', v.children[6].firstChild.value);
oListItem.set_item('GLCode', v.children[7].firstChild.value);
oListItem.set_item('Amount', v.children[8].firstChild.value);
oListItem.set_item('Date', $("#aprDate").val());
oListItem.set_item('Comment', $("#cmt").val());
oListItem.update();
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}
});
}
catch(err)
{
alert(err.message);
}
});
}
function onQuerySucceeded()
{
amtCount = amtCount + 1;
updatePendingInvoice(amtCount);
}
function onQueryFailed(sender, args)
{
alert('not inserted');
}
This runs fine but if the HTML Button is clicked quickly, the function runs and creates duplicate data.

You should disable the button while you are acting on the click. Then the user cannot queue up another update until the first one finishes. Set an internal variable saying that the work is in progress, disable the button, and then clear the flag when you get the result (success or fail).
For instance:
$("#btnSubmit").click(function() {
$("#btnSubmit").prop("disabled", true);
// do your work here, waiting for success or failure
$('#btnSubmit').prop("disabled", false);
})
or:
$("button").click(function(e) {
$(e.currentTarget).prop('disabled', true);
window.setTimeout(function() {
$(e.currentTarget).prop('disabled', false);
}, 5000);
})

I found what I needed and with some experimentation with where to put the "disabled", false lines was able to get to the solution. I got the simple code from Palash
https://stackoverflow.com/users/1823841/palaѕн
All versions of jQuery after 1.6
Disabling and enabling a html input button
Thank you all for helping... New Code....
var amtCount = 0;
function addToLineItem()
{
**$("#IApprove").attr("disabled", true);**
var totalAmount = 0.0;
var valid = true;
var difference = [];
$.each($(".tbodys tr"),function(index,vs)
{
for(var tdcnt = 0; tdcnt < vs.children.length - 1; tdcnt++)
{
if(tdcnt != 5)
if(vs.children[tdcnt].firstElementChild.value == "" || vs.children[tdcnt].firstElementChild.value == undefined)
valid = false;
}
if(vs.children[9].firstChild.value != "" && vs.children[9].firstChild.value != undefined)
{
RMID.push(vs.children[9].firstChild.value);
}
});
if(CodingListItem.length > 0)
{
difference = arr_diff(CodingListItem,RMID);
}
if(valid == false)
{
alert("Please add Line Items with Required Information. GL coding missing.");
**$("#IApprove").attr("disabled", false);**
return false;
}
if($("#aprDate").val() == "")
{
alert("Please add approver date.");
**$("#IApprove").attr("disabled", false);**
return false;
}
$.each($(".tbodys tr .nine"),function(index,vs){
totalAmount += parseFloat(vs.firstElementChild.value.replace(/,/g, ""));
});
if($("#Total")[0].innerText == "")
{
alert("Please add Line items.");
**$("#IApprove").attr("disabled", false);**
return false;
}
//if(parseFloat($("#invTotal").val().replace(/,/g, "")) != totalAmount)
if(parseFloat($("#invTotal").val().replace(/,/g, "")) != parseFloat($("#Total")[0].innerText.replace(/,/g, "")))
{
alert("Line item's total amount does not match with total invoice amount.");
**$("#IApprove").attr("disabled", false);**
return false;
}
SP.SOD.executeFunc("sp.js", 'SP.ClientContext', function()
{
try
{
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var oList = clientContext.get_web().get_lists().getByTitle('Invoice Approval and Coding');
///////////// Delete Items //////////////////
if(difference.length > 0)
{
$.each(difference, function( index, value )
{
deleteListItem(parseInt(value));
});
}
$.each($(".tbodys tr"),function(i,v)
{
if(v.children[9].firstChild.value != "" && v.children[9].firstChild.value != undefined)
{
var itemType1 = GetItemTypeForListName("InvoiceLineItem");
var item1 = {
"__metadata": { "type": itemType1 },
"Title": v.children[0].firstChild.value,
"InvoiceIDId": parseInt(INV),
"Entity": v.children[1].firstChild.value,
"MS": v.children[2].firstChild.value,
"LocationId": parseInt(v.children[3].firstChild.value),
"DepartmentId": parseInt(v.children[4].firstChild.value),
"Account": v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text,
"SubAccount": v.children[6].firstChild.value,
"GLCode": v.children[7].firstChild.value,
"Amount": v.children[8].firstChild.value
};
updateListItem(parseInt(v.children[9].firstChild.value), "Invoice Approval and Coding", _spPageContextInfo.webAbsoluteUrl, item1, function () {
amtCount = amtCount + 1;
updatePendingInvoice(amtCount);
}, function () { errorMsg = true; });
}
else
{
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', v.children[0].firstChild.value); //Line Description
oListItem.set_item('InvoiceID', INV);
oListItem.set_item('Entity', v.children[1].firstChild.value);
oListItem.set_item('MS', v.children[2].firstChild.value);
oListItem.set_item('Location', v.children[3].firstChild.value);
oListItem.set_item('Department', v.children[4].firstChild.value);
oListItem.set_item('Account', v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text);
oListItem.set_item('SubAccount', v.children[6].firstChild.value);
oListItem.set_item('GLCode', v.children[7].firstChild.value);
oListItem.set_item('Amount', v.children[8].firstChild.value);
oListItem.set_item('Date', $("#aprDate").val());
oListItem.set_item('Comment', $("#cmt").val());
oListItem.update();
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}
});
}
catch(err)
{
alert(err.message);
}
});
}

Related

I obfuscated my JavaScript. How can someone exactly decode it?

var _0x3424=["\x67\x65\x74","\x2F\x73\x68\x6F\x70\x2F\x61\x6C\x6C","\x69\x6E\x64\x65\x78\x4F\x66","\x68\x72\x65\x66","\x6C\x6F\x63\x61\x74\x69\x6F\x6E","\x6B\x65\x79\x77\x6F\x72\x64","","\x74\x6F\x4C\x6F\x77\x65\x72\x43\x61\x73\x65","\x63\x6F\x6C\x6F\x72","\x73\x69\x7A\x65","\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65","\x67\x65\x74\x41\x74\x74\x72\x69\x62\x75\x74\x65","\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65\x20\x3E\x20\x61","\x2F","\x73\x70\x6C\x69\x74","\x6C\x65\x6E\x67\x74\x68","\x61\x6C\x74","\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65\x20\x3E\x20\x61\x20\x3E\x20\x69\x6D\x67","\x6E\x6F\x74\x20\x66\x6F\x75\x6E\x64","\x6C\x6F\x67","\x68\x74\x74\x70\x3A\x2F\x2F\x77\x77\x77\x2E\x73\x75\x70\x72\x65\x6D\x65\x6E\x65\x77\x79\x6F\x72\x6B\x2E\x63\x6F\x6D\x2F\x73\x68\x6F\x70\x2F\x61\x6C\x6C","\x3A\x76\x69\x73\x69\x62\x6C\x65","\x69\x73","\x2E\x69\x6E\x2D\x63\x61\x72\x74","\x74\x65\x78\x74","\x73\x65\x6C\x65\x63\x74\x65\x64\x49\x6E\x64\x65\x78","\x70\x72\x6F\x70","\x23\x73\x69\x7A\x65","\x65\x61\x63\x68","\x23\x73\x69\x7A\x65\x20\x6F\x70\x74\x69\x6F\x6E","\x63\x6C\x69\x63\x6B","\x5B\x6E\x61\x6D\x65\x3D\x22\x63\x6F\x6D\x6D\x69\x74\x22\x5D","\x69\x73\x63\x68\x65\x63\x6B\x6F\x75\x74","\x73\x68\x6F\x70\x2F\x61\x6C\x6C","\x68\x74\x74\x70\x73\x3A\x2F\x2F\x77\x77\x77\x2E\x73\x75\x70\x72\x65\x6D\x65\x6E\x65\x77\x79\x6F\x72\x6B\x2E\x63\x6F\x6D\x2F\x63\x68\x65\x63\x6B\x6F\x75\x74","\x73\x65\x6E\x64\x4D\x65\x73\x73\x61\x67\x65","\x65\x78\x74\x65\x6E\x73\x69\x6F\x6E"];$(function(){chrome[_0x3424[36]][_0x3424[35]]({method:_0x3424[0]},function(_0xc165x1){var _0xc165x2=false;var _0xc165x3=setInterval(function(){if(window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[1])!=-1&&_0xc165x2===false){if(_0xc165x1[_0x3424[5]]!=_0x3424[6]&&_0xc165x1[_0x3424[5]]!=undefined){var _0xc165x4=_0xc165x1[_0x3424[5]][_0x3424[7]]();var _0xc165x5=_0xc165x1[_0x3424[8]][_0x3424[7]]();for(var _0xc165x6=0;_0xc165x6<$(_0x3424[10])[_0x3424[9]]();_0xc165x6++){var _0xc165x7=$(_0x3424[12])[_0xc165x6][_0x3424[11]](_0x3424[3]);var _0xc165x8=_0xc165x7[_0x3424[14]](_0x3424[13]);_0xc165x8=_0xc165x8[_0xc165x8[_0x3424[15]]-1][_0x3424[7]]();var _0xc165x9=$(_0x3424[17])[_0xc165x6][_0x3424[11]](_0x3424[16])[_0x3424[7]]();if(_0xc165x9[_0x3424[2]](_0xc165x4)!=-1&&_0xc165x8[_0x3424[2]](_0xc165x5)!=-1&&_0xc165x2===false){_0xc165x2=true;window[_0x3424[4]][_0x3424[3]]=_0xc165x7;break ;}else {console[_0x3424[19]](_0x3424[18])};};if(_0xc165x2===false){clearInterval(_0xc165x3);window[_0x3424[4]][_0x3424[3]]=_0x3424[20];};}}});var _0xc165xa=setInterval(function(){if(window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[1])== -1){if(!$(_0x3424[23])[_0x3424[22]](_0x3424[21])){$(_0x3424[29])[_0x3424[28]](function(_0xc165x6){if($(this)[_0x3424[24]]()==_0xc165x1[_0x3424[9]]){$(_0x3424[27])[_0x3424[26]](_0x3424[25],_0xc165x6)}});$(_0x3424[31])[_0x3424[30]]();}}},100);if(_0xc165x1[_0x3424[32]]==1){var _0xc165xb=setInterval(function(){if($(_0x3424[23])[_0x3424[22]](_0x3424[21])&&window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[33])== -1){window[_0x3424[4]]=_0x3424[34];clearInterval(_0xc165xb);}},100)};})});
I'm wondering if this is a strong encryption, how could someone exactly decode it? Any help would be appreciate. Thank you.
It's impossible to recover the EXACT original code once it's obfuscated, but keep in mind that the code still needs to be understandable by the compiler/interpreter so it may be "reassembled" but most likely the original structure, classes, variable names, etc... will be lost.
My try to deobfuscate your code got me this :
var _0x3424 = ["\x67\x65\x74", "\x2F\x73\x68\x6F\x70\x2F\x61\x6C\x6C", "\x69\x6E\x64\x65\x78\x4F\x66", "\x68\x72\x65\x66", "\x6C\x6F\x63\x61\x74\x69\x6F\x6E", "\x6B\x65\x79\x77\x6F\x72\x64", "", "\x74\x6F\x4C\x6F\x77\x65\x72\x43\x61\x73\x65", "\x63\x6F\x6C\x6F\x72", "\x73\x69\x7A\x65", "\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65", "\x67\x65\x74\x41\x74\x74\x72\x69\x62\x75\x74\x65", "\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65\x20\x3E\x20\x61", "\x2F", "\x73\x70\x6C\x69\x74", "\x6C\x65\x6E\x67\x74\x68", "\x61\x6C\x74", "\x2E\x69\x6E\x6E\x65\x72\x2D\x61\x72\x74\x69\x63\x6C\x65\x20\x3E\x20\x61\x20\x3E\x20\x69\x6D\x67", "\x6E\x6F\x74\x20\x66\x6F\x75\x6E\x64", "\x6C\x6F\x67", "\x68\x74\x74\x70\x3A\x2F\x2F\x77\x77\x77\x2E\x73\x75\x70\x72\x65\x6D\x65\x6E\x65\x77\x79\x6F\x72\x6B\x2E\x63\x6F\x6D\x2F\x73\x68\x6F\x70\x2F\x61\x6C\x6C", "\x3A\x76\x69\x73\x69\x62\x6C\x65", "\x69\x73", "\x2E\x69\x6E\x2D\x63\x61\x72\x74", "\x74\x65\x78\x74", "\x73\x65\x6C\x65\x63\x74\x65\x64\x49\x6E\x64\x65\x78", "\x70\x72\x6F\x70", "\x23\x73\x69\x7A\x65", "\x65\x61\x63\x68", "\x23\x73\x69\x7A\x65\x20\x6F\x70\x74\x69\x6F\x6E", "\x63\x6C\x69\x63\x6B", "\x5B\x6E\x61\x6D\x65\x3D\x22\x63\x6F\x6D\x6D\x69\x74\x22\x5D", "\x69\x73\x63\x68\x65\x63\x6B\x6F\x75\x74", "\x73\x68\x6F\x70\x2F\x61\x6C\x6C", "\x68\x74\x74\x70\x73\x3A\x2F\x2F\x77\x77\x77\x2E\x73\x75\x70\x72\x65\x6D\x65\x6E\x65\x77\x79\x6F\x72\x6B\x2E\x63\x6F\x6D\x2F\x63\x68\x65\x63\x6B\x6F\x75\x74", "\x73\x65\x6E\x64\x4D\x65\x73\x73\x61\x67\x65", "\x65\x78\x74\x65\x6E\x73\x69\x6F\x6E"];
$(function() {
chrome[_0x3424[36]][_0x3424[35]]({
method: _0x3424[0]
}, function(_0xc165x1) {
var _0xc165x2 = false;
var _0xc165x3 = setInterval(function() {
if (window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[1]) != -1 && _0xc165x2 === false) {
if (_0xc165x1[_0x3424[5]] != _0x3424[6] && _0xc165x1[_0x3424[5]] != undefined) {
var _0xc165x4 = _0xc165x1[_0x3424[5]][_0x3424[7]]();
var _0xc165x5 = _0xc165x1[_0x3424[8]][_0x3424[7]]();
for (var _0xc165x6 = 0; _0xc165x6 < $(_0x3424[10])[_0x3424[9]](); _0xc165x6++) {
var _0xc165x7 = $(_0x3424[12])[_0xc165x6][_0x3424[11]](_0x3424[3]);
var _0xc165x8 = _0xc165x7[_0x3424[14]](_0x3424[13]);
_0xc165x8 = _0xc165x8[_0xc165x8[_0x3424[15]] - 1][_0x3424[7]]();
var _0xc165x9 = $(_0x3424[17])[_0xc165x6][_0x3424[11]](_0x3424[16])[_0x3424[7]]();
if (_0xc165x9[_0x3424[2]](_0xc165x4) != -1 && _0xc165x8[_0x3424[2]](_0xc165x5) != -1 && _0xc165x2 === false) {
_0xc165x2 = true;
window[_0x3424[4]][_0x3424[3]] = _0xc165x7;
break;
} else {
console[_0x3424[19]](_0x3424[18])
};
};
if (_0xc165x2 === false) {
clearInterval(_0xc165x3);
window[_0x3424[4]][_0x3424[3]] = _0x3424[20];
};
}
}
});
var _0xc165xa = setInterval(function() {
if (window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[1]) == -1) {
if (!$(_0x3424[23])[_0x3424[22]](_0x3424[21])) {
$(_0x3424[29])[_0x3424[28]](function(_0xc165x6) {
if ($(this)[_0x3424[24]]() == _0xc165x1[_0x3424[9]]) {
$(_0x3424[27])[_0x3424[26]](_0x3424[25], _0xc165x6)
}
});
$(_0x3424[31])[_0x3424[30]]();
}
}
}, 100);
if (_0xc165x1[_0x3424[32]] == 1) {
var _0xc165xb = setInterval(function() {
if ($(_0x3424[23])[_0x3424[22]](_0x3424[21]) && window[_0x3424[4]][_0x3424[3]][_0x3424[2]](_0x3424[33]) == -1) {
window[_0x3424[4]] = _0x3424[34];
clearInterval(_0xc165xb);
}
}, 100)
};
})
});
OK, how'd I do. Variable names will have changed of course, but the functionality of the code is completely readable
$(function () {
chrome.extension.sendMessage({ method: "get" },
function (param1) {
var var1 = false;
var intHand1 = setInterval(function () {
if (window.location.href.indexOf("/shop/all") != -1 && var1 === false) {
if (param1.keyword != "" && param1.keyword != undefined) {
var kwordlc = param1.keyword.toLowerCase();
var colorlc = param1.color.toLowerCase();
for (var i = 0; i < $(".inner-article").size() ; i++) {
var ahref = $(".inner-article > a")[i].getAttribute("href");
var ahrefsplit = ahref.split("/");
ahrefsplit = ahrefsplit[ahrefsplit.length - 1].toLowerCase();
var altlc = $(".inner-article > a > img")[i].getAttribute("alt").toLowerCase();
if (altlc.indexOf(kwordlc) != -1 && ahrefsplit.indexOf(colorlc) != -1 && var1 === false) {
var1 = true;
window.location.href = ahref;
break;
} else {
console.log("not found")
};
}; if (var1 === false) {
clearInterval(intHand1);
window.location.href = "http://www.supremenewyork.com/shop/all";
};
}
}
});
var intHand2 = setInterval(function () {
if (window.location.href.indexOf("/shop/all") == -1) {
if (!$(".in-cart").is(":visible")) {
$("#size option").each(function (param2) {
if ($(this).text() == param1.size) {
$("#size").prop("selectedIndex", param2)
}
}); $("[name='commit']").click();
}
}
}, 100);
if (param1.ischeckout == 1) {
var intHand3 = setInterval(function () {
if ($(".in-cart").is(":visible") && window.location.href.indexOf("shop/all") == -1) {
window.location = "https://www.supremenewyork.com/checkout";
clearInterval(intHand3);
}
}, 100)
};
})
});
Took me about 50 mins, and I got interrupted by a couple of phone calls, messages and emails.

Could someone explain why my functions are not working?

So I'm very new to JavaScript and I'm trying a very simple enter text and check it. It doesn't seem to work the way I want it to. I want all of the inputs to go through the checkInputs. After All of them are 100% I want it to check if hoursWorked and horlyRate are numbers above 0. It seems to just move on to the checkNumberValidation without checking if all inputs are filled.
I got:
function checkNumbersValidation(field){
if( isNaN(field) ) {
field.value = "Must be a number";
field.focus("");
}
}
function checkInputs(field) {
var test = false;
do{
if ( field.value === null || field.value.trim() === "" ) {
field.value = "Input needed";
//set focus
field.focus("");
}else if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
}else {
tests = true;
}
}while (test = false)
}
function handelCalcButtonClicked (e) {
var passFirstTests = false;
var textFields = ["fullName", "hoursWorked", "hourlyRate"];
for( var i = 0; i < textFields.length; i ++ ) {
var field = document.getElementById(textFields[i]);
checkInputs(field);
}
if( **something** ) {
var numberFields = ["hoursWorked", "hourlyRate"]
for ( var i = 0; i < numberFields.length; i++ ) {
field = document.getElementById(numberFields[i]);
checkNumbersValidation(field);
}
}
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});
clearly I don't know what I'm doing. In the function handelCalcButtonClicked I'm not sure how to move on the the next part (the part Saying something). Any help would be nice!
Inside checkNumbersValidation you need to do the isNan call on field.value, not field:
if( isNaN(field.value) )
If you want to know if all of your fields have gone through checkInputs and have passed, you will need checkInputs to return whether or not each field has passed:
function checkInputs(field) {
if ( field.value === null || field.value.trim() === "" ) {
field.value = "Input needed";
//set focus
field.focus("");
return false;
} else if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
return false;
}
return true;
}
This will allow you to know if all fields have passed the check:
var passedAllChecks = true;
for( var i = 0; i < textFields.length; i ++ ) {
var field = document.getElementById(textFields[i]);
passedAllChecks = checkInputs(field) && passedAllChecks;
}
if(passedAllChecks) {
/* do number validation stuff */
}
What about this:
function checkNumbersValidation(field) {
if (isNaN(field)) {
field.value = "Must be a number";
field.focus("");
}
}
function checkInputs(field) {
if (!field.value || !field.value.trim()) {
field.value = "Input needed";
field.focus("");
return;
if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
}
}
function handelCalcButtonClicked (e) {
var textFields = ["fullName", "hoursWorked", "hourlyRate"],
numberFields = [ "hoursWorked", "hourlyRate"],
i,
field;
for (i = 0; i < textFields.length; i++) {
field = document.getElementById(textFields[i]);
checkInputs(field);
}
for (i = 0; i < numberFields.length; i++) {
field = document.getElementById(numberFields[i]);
checkNumbersValidation(field);
}
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});
or:
function checkInput(field, isnumber) {
if (!field) return;
if (isnumber === true && isNaN(field)) {
field.value = "Must be a number";
field.focus("");
return;
}
if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
return;
}
if (!field.value || !field.value.trim()) {
field.value = "Input needed";
field.focus("");
}
}
function handelCalcButtonClicked (e) {
checkInput(document.getElementById('fullName');
checkInput(document.getElementById('hoursWorked', true);
checkInput(document.getElementById('hourlyRate', true);
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});

Validate form function jump to error?

I have a form with a validation script that works perfectly. I would however like the form to jump to the fields that doesn't validate or display the name of the fields in the error message.
The code I use to validate is:
else
{
var valid = document.formvalidator.isValid(f);
}
if (flag == 0 || valid == true) {
f.check.value = '<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('There was an error with the fields..');
return false;
}
return true;
How can I get the alert to name the fields that need to be filled in correctly or jump to the specific field?
Edited ----------
Hi,
Thanks for help so far. I'm very new to JS. The form is in a component of Joomla.
The full function that validates the form is
function validateForm(f){
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer"){
var flag = 0;
for (var i=0;i < f.elements.length; i++) {
el = f.elements[i];
if ($(el).hasClass('required')) {
var idz= $(el).getProperty('id');
if(document.getElementById(idz)){
if (!document.getElementById(idz).value) {
document.formvalidator.handleResponse(false, el);
flag = flag + 1;
}
}
}
}
}
else {
var valid = document.formvalidator.isValid(f);
}
if(flag == 0 || valid == true){
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('<?php echo JText::_('JBJOBS_FIEDS_HIGHLIGHTED_RED_COMPULSORY'); ?>');
return false;
}
return true;
}
External js file:
var JFormValidator = new Class(
{
initialize : function() {
this.handlers = Object();
this.custom = Object();
this.setHandler("username", function(b) {
regex = new RegExp("[<|>|\"|'|%|;|(|)|&]", "i");
return !regex.test(b)
});
this.setHandler("password", function(b) {
regex = /^\S[\S ]{2,98}\S$/;
return regex.test(b)
});
this.setHandler('passverify',
function (value) {
return ($('password').value == value);
}
); // added March 2011
this.setHandler("numeric", function(b) {
regex = /^(\d|-)?(\d|,)*\.?\d*$/;
return regex.test(b)
});
this
.setHandler(
"email",
function(b) {
regex = /^[a-zA-Z0-9._-]+(\+[a-zA-Z0-9._-]+)*#([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
return regex.test(b)
});
var a = $$("form.form-validate");
a.each(function(b) {
this.attachToForm(b)
}, this)
},
setHandler : function(b, c, a) {
a = (a == "") ? true : a;
this.handlers[b] = {
enabled : a,
exec : c
}
},
attachToForm : function(a) {
a.getElements("input,textarea,select")
.each(
function(b) {
if (($(b).get("tag") == "input" || $(b)
.get("tag") == "button")
&& $(b).get("type") == "submit") {
if (b.hasClass("validate")) {
b.onclick = function() {
return document.formvalidator
.isValid(this.form)
}
}
} else {
b.addEvent("blur", function() {
return document.formvalidator
.validate(this)
})
}
})
},
validate : function(c) {
c = $(c);
if (c.get("disabled")) {
this.handleResponse(true, c);
return true
}
if (c.hasClass("required")) {
if (c.get("tag") == "fieldset"
&& (c.hasClass("radio") || c.hasClass("checkboxes"))) {
for ( var a = 0;; a++) {
if (document.id(c.get("id") + a)) {
if (document.id(c.get("id") + a).checked) {
break
}
} else {
this.handleResponse(false, c);
return false
}
}
} else {
if (!(c.get("value"))) {
this.handleResponse(false, c);
return false
}
}
}
var b = (c.className && c.className
.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? c.className
.match(/validate-([a-zA-Z0-9\_\-]+)/)[1]
: "";
if (b == "") {
this.handleResponse(true, c);
return true
}
if ((b) && (b != "none") && (this.handlers[b])
&& c.get("value")) {
if (this.handlers[b].exec(c.get("value")) != true) {
this.handleResponse(false, c);
return false
}
}
this.handleResponse(true, c);
return true
},
isValid : function(c) {
var b = true;
var d = c.getElements("fieldset").concat($A(c.elements));
for ( var a = 0; a < d.length; a++) {
if (this.validate(d[a]) == false) {
b = false
}
}
new Hash(this.custom).each(function(e) {
if (e.exec() != true) {
b = false
}
});
return b
},
handleResponse : function(b, a) {
if (!(a.labelref)) {
var c = $$("label");
c.each(function(d) {
if (d.get("for") == a.get("id")) {
a.labelref = d
}
})
}
if (b == false) {
a.addClass("invalid");
a.set("aria-invalid", "true");
if (a.labelref) {
document.id(a.labelref).addClass("invalid");
document.id(a.labelref).set("aria-invalid", "true");
}
} else {
a.removeClass("invalid");
a.set("aria-invalid", "false");
if (a.labelref) {
document.id(a.labelref).removeClass("invalid");
document.id(a.labelref).set("aria-invalid", "false");
}
}
}
});
document.formvalidator = null;
window.addEvent("domready", function() {
document.formvalidator = new JFormValidator()
});
Where would I edit the code as some of you have answered below?
with jquery js library, scroll to element (id selector or class)
<p class="error">There was a problem with this element.</p>
This gets passed to the ScrollTo plugin in the following way.
$.scrollTo($('p.error:1'));
see source
Using jQuery's .each, loop over the fields. On every iteration the item that is being invesitigated will be under the this variable.
Therefore, this.id gives the id of the element you're looking for. Store these to collect all the incorrect fields, then highlight them or print their names in a message.
Keep in mind, this is the basic idea, I cannot give an actual answer until you show the code that handles the form.
Kind regards,
D.
You can have your isValid routine return the error message instead of returning a boolean.
In isValid, you can build up the error message to include the field names with errors.
Instead of checking "valid == true", you will check "errorMessage.length == 0".
If you want to focus on an error field (you can only focus on one), then do that in the isValid routine as well.
function isValid(f) {
var errorMessage = "";
var errorFields = "";
var isFocused = false;
...
if (field has an error) {
errorFields += " " + field.name;
if (!isFocused) {
field.focus();
isFocused = true;
}
}
...
if (errorFields.length > 0) {
errorMessage = "Errors in fields: " + errorFields;
}
return (errorMessage);
}
then, in your calling routine:
var errorMessage = isValid(f);
if (flag == 0 || errorMessage.length == 0) {
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert(errorMessage);
return false;
}
return true;

How to import data of gmail contacts, using javascript Google Contact API, in more detailed format?

I'm using code from this page http://code.google.com/apis/contacts/docs/1.0/developers_guide_js.html to get list of gmail contacts. Actually it works ok, but I get data of name, address, etc like a simple string, with "\n" as separator, for example:
<script type="text/javascript">
var contactsService;
var scope = 'https://www.google.com/m8/feeds';
function setupContactsService() {
//contactsService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
contactsService = new google.gdata.contacts.ContactsService('GoogleInc-jsguide-1.0');
}
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full'; //?max-results=9999&alt=json&v=3.0
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
setupContactsService();
contactsService.getContactFeed(query, handleContactsFeed, handleError);
}
var handleContactsFeed = function(result) {
var entries = result.feed.entry;
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var addrs = entry.getPostalAddresses();
var name = entry.getTitle();
// logging
console.log(addrs[0]);
console.log(name);
}
}
function handleError(e) {
alert(e.cause ? e.cause.statusText : e.message);
}
</script>
it gives me an object where name and address values are simple strings.
Can I get somehow data in like associative array format, where address will contains separate values of street, zip, city, country; and name separate values of first name, last name etc.
Like:
{
"type": "address",
"value":
{
"street": "Starret 1234",
"city": "City name",
"stateOrProvince": "ca",
"postalCode": "73000",
"country": "USA"
}
},
{
"type": "name",
"value":
{
"firstName": "Allen",
"lastName" : "Iverson",
.....
}
}
Thanks in advance!
Seems I found an answer, for get more detailed and formatted info need to add additional parameter to contactsFeedUri for google.gdata.contacts.ContactQuery.
This additional parameter is: ?v=3.0
So in my case function will looks like:
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full?v=3.0&alt=json';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
setupContactsService();
contactsService.getContactFeed(query, handleContactsFeed, handleError);
}
And for get necessary data I create a simple obj, which can be useful for somebody:
function contactEntry(entry) {
this.entry = entry;
this.testEntry = function() {
alert( 'test entry' )
};
this.getFirstName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$givenName == null) || (entry.gd$name.gd$givenName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$givenName.$t;
}
};
this.getLastName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$familyName == null) || (entry.gd$name.gd$familyName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$familyName.$t;
}
};
this.getAdditionalName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$AdditionalName == null) || (entry.gd$name.gd$AdditionalName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$familyName.$t;
}
};
this.getEmail = function() {
if ((entry.gd$email == null) || (entry.gd$email.length == 0) || (entry.gd$email[0].address == null)) {
return '';
} else {
return entry.gd$email[0].address;
}
};
this.getStreet = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$street == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$street.$t;
}
};
this.getCity = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$city == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$city.$t;
}
};
this.getCountry = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$country == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$country.$t;
}
};
this.getPostcode = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$postcode == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$postcode.$t;
}
};
this.getPhone = function() {
if ((entry.gd$phoneNumber == null) || (entry.gd$phoneNumber.length == 0) || (entry.gd$phoneNumber[0].$t == null)) {
return '';
} else {
return entry.gd$phoneNumber[0].$t
}
};
this.getOrganization = function() {
if ((entry.gd$organization == null) || (entry.gd$organization.length == 0) || (entry.gd$organization[0].getOrgName() == null)) {
return '';
} else {
return entry.gd$organization[0].getOrgName().getValue();
}
};
this.getBirthday = function() {
if ((entry.gContact$birthday == null) || (entry.gContact$birthday.when == null)) {
return '';
} else {
return entry.gContact$birthday.when;
}
};
this.getEvent = function() {
if ((entry.gContact$event == null) || (entry.gContact$event.length == 0) || (entry.gContact$event[0].gd$when == null)) {
return '';
} else {
return entry.gContact$event[0].gd$when.startTime;
}
};
// protected methods
this._addrExists = function() {
if ((entry.gd$structuredPostalAddress == null) || (entry.gd$structuredPostalAddress.length == 0)) {
return false;
}
return true;
};
}
It can be used in this way:
var handleContactsFeed = function(result) {
var entries = result.feed.entry;
var contact = new contactEntry(entries[0]);
var address = {};
address['fname'] = contact.getFirstName();
address['lname'] = contact.getLastName() + (contact.getAdditionalName() != '' ? ' ' + contact.getAdditionalName() : '');
address['address'] = contact.getStreet();
address['city'] = contact.getCity();
address['country'] = contact.getCountry();
address['zip'] = contact.getPostcode();
address['phone'] = contact.getPhone();
address['mail'] = contact.getEmail();
address['organization'] = contact.getOrganization();
address['birthday'] = contact.getBirthday();
address['event'] = contact.getEvent();
}

Null error is coming document.getElementByid("dthchannel" + [i] is null)

function validate()
{
var flag=0;
var spchar=/^[a-zA-Z0-9 ]*$/;
var num=/^[0-9]*$/;
var custid = document.getElementById('CUSTOMERID').value;
var phoNo = document.getElementById('PHONENO').value;
var emailId = document.getElementById('EMAILID').value;
var channel = document.getElementById('CHANNELDTL').value;
if(channel=="")
{
alert("You have not selected any channel");
flag=1;
return false;
}
if(custid=="" || custid==null )
{
alert("Please enter Customer ID");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if (custid.search(num)==-1)
{
alert("Customer should be Numeric");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if(phoNo=="" || phoNo==null )
{
alert("Please enter Phone");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if (phoNo.search(num)==-1)
{
alert("Phone should be Numeric");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if(emailId=="" || emailId==null )
{
alert("Please enter Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
if (emailId)
{
if(isValidEmail(document.getElementById('EMAILID').value) == false)
{
alert("Please enter valid Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
}
if(flag==0)
{
var emailid=Base64.tripleEncoding(document.getElementById('EMAILID').value);
document.getElementById('E_EMAIL').value=emailid;
document.getElementById('EMAILID').value="";
var mobileno=Base64.tripleEncoding(document.getElementById('PHONENO').value);
document.getElementById('E_PHONE').value=mobileno;
document.getElementById('PHONENO').value="";
var customerid=Base64.tripleEncoding(document.getElementById('CUSTOMERID').value);
document.getElementById('E_CUSTID').value=customerid;
document.getElementById('CUSTOMERID').value="";
document.topupsform.action="../dth/leads/channelMail/channelMailUtil.jsp";
document.topupsform.submit();
alert("Thank you for choosing A-La-Carte services.\nWe will process it within 24 hours.\nYou will soon receive confirmation on your mail id.");
}
}
function isValidEmail(Email)
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = trim(Email);
if(reg.test(address) == false)
{
return false;
}
else
return true;
}
function trim(str)
{
str = this != window? this : str;
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function sendMail()
{
caltotal();
validate();
}
//----------------------------------
var counter = 0;
function resetcheckboxValue(){
//var totalinputs = document.topupsform.getElementsByTagName("input");
var totalinputs =document.getElementsByName("dthchannel");
var totallenght = totalinputs.length;
counter = 0;
for(var i = 0; i < totallenght; i++) {
// reset all checkboxes
document.getElementsByName("dthchannel")[i].checked = false;
document.getElementById("totalamount").value = "0";
document.getElementById("youpay").value = "0";
}
}
function caltotal()
{
var plansObj = document.getElementsByName("dthchannel");
var plansLength = plansObj.length;
counter = 0;
var finalNameValue = "";
for(var i = 1; i <= plansObj.length+1; i++) {
if ( document.getElementById(("dthchannel")+ [i]).checked)
{
var gvalue = parseInt(document.getElementById(("dthchannel")+[i]).value);
var gNameValue= document.getElementById("CHANNELNAME"+i).value+"~"+gvalue+"#";
finalNameValue+= gNameValue;
counter+= gvalue;
}
showresult();
}
var finallist = finalNameValue.substring(0,finalNameValue.length-1);
//alert("finallist" +finallist);
document.getElementById("CHANNELDTL").value= finallist;
}
function showresult(){
if(counter <= 150 && counter > 0){
document.getElementById("youpay").value = "150";
document.getElementById("totalamount").value = counter;
}
else
{
document.getElementById("youpay").value = counter;
document.getElementById("totalamount").value = counter;
}
}
window.onload = resetcheckboxValue;
You need to modify whatever lines look like this:
var gvalue = parseInt(document.getElementById("dthchannel" + i).value);
You don't want to do document.getElementById(("dthchannel") + [i]) as I've never seen that before and I don't think it works.

Categories

Resources