How to parse string correctly into onclick method - javascript

I have a dynamic table which is being created with jquery. The problem I face is, jquery interferes my string so it's not being parsed correctly to onclick method.
for (var i = 0; i < data.result.list.length; i++)
{
var tr = $("<tr></tr>");
tr.append("<td>" + "<a onclick='" + data.result.list[i].cfunction + "'>" + data.result.list[i].cvalue + "</a>" + "</td>");
tr.append("<td>" + + "</td>");
table.append(tr);
}
data.result.list[i].cfunction has a string value like "getMyMethod('My parameter')" which is basically calling a method with parameter in quotes.
But after jQuery parses this to onclick function it's value changes as onclick="getMyMethod(" my="" parameter')'=""
here is the generated html:
<a onclick="getMyMethod(" my="" parameter')'="" >My Value</a>
Can anyone put me in the right direction?

Change this line
"<a onclick='" + data.result.list[i].cfunction + "'>"
to this
'<a onclick="' + data.result.list[i].cfunction + '">'

You internal double quotes " needs to be escaped
var func = data.result.list[i].cfunction.replace( /"/g, "\\\"" );
tr.append("<td>" + "<a onclick='" + func + "'>" + data.result.list[i].cvalue + "</a>" + "</td>");

you should modify code with:
tr.append(
$("<td></<td>").append(
$("<a></a>")
.attr({
"href" : "#"
})
.text(data.result.list[i].cvalue)
.attr({
"onclick" : data.result.list[i].cfunction
})
)
);

You can modify your cfunction items in the data like this (encode):
cfunction: "getMyMethod(\"My parameter\")",
This worked in the console (make sure the table ID exists):
var data = {
result: {
list: [
{
cfunction: "getMyMethod(\"My parameter 1\")",
cvalue: "1"
},
{
cfunction: "getMyMethod(\"My parameter 2\")",
cvalue: "2"
}
]
}
}
var table = $("#testTable");
for (var i = 0; i < data.result.list.length; i++) {
var tr = $("<tr></tr>");
tr.append("<td>" + "<a onclick='" + data.result.list[i].cfunction + "'>" + data.result.list[i].cvalue + "</a>" + "</td>");
tr.append("<td>" + + "</td>");
table.append(tr);
}
var getMyMethod = function (funcParam) {
console.log(funcParam);
};

Can you try this. And be sure your data.result.list[i].cfunction value is
"getMyMethod('My parameter')"
for (var i = 0; i < data.result.list.length; i++)
{
var tr = $("<tr></tr>");
tr.append("<td>" + "<a onclick=\" " + data.result.list[i].cfunction +
"\" >" + data.result.list[i].cvalue + "</a>" + "</td>");
tr.append("<td>" + + "</td>");
table.append(tr);
}

Related

Delete Firebase Node with OnClick Function JavaScript

I have two JavaScript functions, one to generate a table and the other to delete a row by removing the node from the Firebase database. I keep getting an error that says deleteRecord() function is undefined. Please assist...
function generate_table(){
$('#emp_body').html('');
console.log(dArr);
for (var i = 0; i < dArr.length; i++) {
var tr;
tr = $('<tr/>');
var strSleeve = "View Sleeve";
var sleeveLink = strSleeve.link(dArr[i][1].downloadURLSleeve);
var strAud = "View Audio";
var audioLink = strAud.link(dArr[i][1].downloadURLFile);
tr.append("<td>" + (i+1) + "</td>");
tr.append("<td>" + childKeys[i] + "</td>");
tr.append("<td>" + dArr[i][1].stageName + "</td>");
tr.append("<td>" + dArr[i][1].fullName + "</td>");
tr.append("<td>" + dArr[i][1].email + "</td>");
tr.append("<td>" + dArr[i][1].city + "</td>");
tr.append("<td>" + dArr[i][1].cell + "</td>");
tr.append("<td>" + sleeveLink + "</td>");
tr.append("<td>" + audioLink + "</td>");
tr.append('<td>' + '<button id="deleteBtn" onclick="deleteRecord(\''+childKeys[i]+'\');" class="btn btn-danger">Delete Record</button>' + '</td>');
$('#emp_body').append(tr);
}
}
// DELETE FUNCTION
function deleteRecord(key){
var refDB = firebase.database().ref().child('submissions/'+key);
refDB.once("value")
.then(function(snapshot) {
snapshot.ref.remove();
alert("Record deleted..!");
}).catch(function(error) {alert("Data could not be deleted." + error);});
}
You should do as follows:
function deleteRecord(key){
var refDB = firebase.database().ref('submissions/' + key);
refDB.remove()
.then(function() {
console.log("Remove succeeded.")
})
.catch(function(error) {
console.log("Remove failed: " + error.message)
});
}
See the corresponding doc here: https://firebase.google.com/docs/reference/js/firebase.database.Reference#remove
You should not use the once() method which is used to read data, as explained here: https://firebase.google.com/docs/reference/js/firebase.database.Reference#once
I figured out a workaround. I think things will get easier from here. For now I am going to use the url to the specific node and delete the item from firebase while I try to figure out a better approach.
function generate_table(){
$('#emp_body').html('');
console.log(dArr);
for (var i = 0; i < dArr.length; i++) {
var tr;
tr = $('<tr/>');
var strSleeve = "View Sleeve";
var sleeveLink = strSleeve.link(dArr[i][1].downloadURLSleeve);
var strAud = "View Audio";
var audioLink = strAud.link(dArr[i][1].downloadURLFile);
tr.append("<td>" + (i+1) + "</td>");
tr.append("<td>" + childKeys[i] + "</td>");
tr.append("<td>" + dArr[i][1].stageName + "</td>");
tr.append("<td>" + dArr[i][1].fullName + "</td>");
tr.append("<td>" + dArr[i][1].email + "</td>");
tr.append("<td>" + dArr[i][1].city + "</td>");
tr.append("<td>" + dArr[i][1].cell + "</td>");
tr.append("<td>" + sleeveLink + "</td>");
tr.append("<td>" + audioLink + "</td>");
var deleteLink = 'https://myFirebaseAuthDomain.firebaseio.com/submissions'+'/'+ childKeys[i];
tr.append('<td>' + '<button id="deleteBtn" class="btn btn-danger">Delete Record</button>' + '</td>');
$('#emp_body').append(tr);
document.getElementById("deleteBtn").onclick = function()
{
console.log("AHOY!" + deleteLink);
var win = window.open(deleteLink, '_blank');
win.focus();
};
}
}
Typically, you fetch the data for the table and at that point Firebase is out of the picture. You take the response data and use JavaScript or whateverScript to build out your UI as you like, in your case you want a table.
I recommend that you add a dataset property to each table row which hold the value of whatever node that row represents, e.g. dataset.myid = a8hKE21Nswtevr applied to each <tr>.
You then appy a click listener to the entire table, or to the rows (by class), and all you have to do is evt.target.parentElement.dataset.myid to get the specific thing the end user clicked.
You then take that uid and talk to firebase as needed.

jquery $.each not giving all the information in the table

Fiddle
I want to put the names of all record in my array into a table my array isn't index correctly so i used $.each instead of iterating over the using for loop. My problem is I only get to show the last element but if i try to show a value that is existing to both the array it is showing correctly.
What am i missing in this code.
Any idea is appreciated
This is my javascript
for (var i = 0; i < name.length; i++) {
var names = name[i].Names;
$.each(names, function (item, names) {
tr = $('<tr class=""/>');
//console.log(complainant[obj]);
//var names = complainant[obj];
//if(names.hasOwnProperty('fname')){
console.log(names.suffix);
var acronymc;
var upper = names.mname.toUpperCase();
if (upper) {
var matches = upper.match(/\b(\w)/g);
//var matches = upper.replace(/^(\S+)\s+(\S).*/, '$1 $2.');
//acronym = upper.slice(0,1);
var acronym1 = matches.join('');
acronymc = acronym1.slice(-1);
} else {
acronymc = '';
}
tr.append("<td id=''>" + "<span id='fname'>" + names.fname + "</span>" + " " + "<span id='mname'>" + acronymc + "</span>" + " " + "<span id='lname'>" + names.lname + "</span>" + " " + "<span id='suffix'>" + names.suffix + "</span>" + "</td>");
tr.append("<td id=''>" + '<span id="street">' + names.street + '</span>' + " " + '<span id="brgy">' + names.brgy + '</span>' + " " + '<span id="town">' + names.town + '</span>' + " " + '<span id="city">' + names.city + '</span>' + "</td>");
tr.append("<td id=''>" + names.contactnum + "</td>");
tr.append("<td id=''>" + "<a href='#' class='editcomplainant'>Edit</a>" + "/" + "<a href='#' class='delete'>Delete</a>" + "</td>");
//}
});
$("#nameslist").append(tr);
}
Put the $('#nameslist').append(tr); call inside the $.each block.
Here is a way of improving the creation of tds:
var html =
"<td>" +
"<span id='fname'/> " +
"<span id='mname'/> " +
"<span id='lname'/> " +
"<span id='suffix'/>" +
"</td>";
var td = $(html);
td.find('#fname').text(names.fname);
td.find('#mname').text(acronymc);
td.find('#lname').text(names.lname);
td.find('#suffix').text(names.suffix);
tr.apppend(td);
Why is this better (imho)?
You will not create unintentional html tags by having < and > inside the variables.
Appropriate escaping (auml codes) will be automatically generated
It is easier to read

ajax data show in table with 10 row

I have an ajax function which select data from database base on entered information i want this information in a table having a format like this
System Id | Last Name | First Name | Middle Name | Address
Here is my ajax
$.ajax({
type: 'POST',
url: '../include/OwnerInformation.php',
dataType: "json",
data: {
lastname: last_name,
firstname: first_name,
sysid: sys_id,
address: address
},
success: function(data) {
console.log(data);
var tr = ("#searchresults");
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + "<a id=" + data[i].sys_id + " href='#' value='" + data[i].sys_id + "'>" + data[i].sys_id + "</a>" + "</td>");
tr.append("<td>" + data[i].firstname + "</td>");
tr.append("<td>" + data[i].middlename + "</td>");
tr.append("<td>" + data[i].lastname + "</td>");
tr.append("<td>" + data[i].address + "," + "</td>");
$('table').append(tr);
}
}
});
I got the tutorial for adding row here but it is not behaving like i want it to.What i want is
Result will show in a specific table (search result table) - ok
The table will have a fix number of row (10 rows)
If the result is below 10 the row will still be 10 if row is more
than 10 it will show the next 10 with next and previous button
For your number 2:
Just use
for (var i = 0; i < 10; i++)
Then if data[i] is null, you could instantiate empty values for data[i]
For your number 3:
You should edit your php so it accept something like table.php?limit=10&startRow=10 (this should fetch the second page)
first of all: The first ("#searchresults") line you forgot to add the dollar sign $. So $("#searchresults").
Secondly: You shouldn't reassign the variable for this kind of task
Finally. My solution:
var table = $("#searchresults");
for (var i = 0; i < 10; i++) {
if(data[i]==null)
data[i] = {};
var tr = $('<tr/>');
tr.append("<td>" + "<a id=" + data[i].sys_id + " href='#' value='" + data[i].sys_id + "'>" + data[i].sys_id + "</a>" + "</td>");
tr.append("<td>" + data[i].firstname + "</td>");
tr.append("<td>" + data[i].middlename + "</td>");
tr.append("<td>" + data[i].lastname + "</td>");
tr.append("<td>" + data[i].address + "," + "</td>");
table.append(tr);
}
i know it's not pretty and maybe cause some problems down the road. But hey!
var data = [
{
firstname:"Heinrich",
middlename:"Lelouch",
lastname:"Breinholdt",
address:"German smurtz"
},
{
firstname:"Cate",
middlename:"Brom",
lastname:"Lriah",
address:"Somewhere"
},
{
firstname:"Funky",
middlename:"Daddy",
lastname:"Man",
address:"Funky land"
}
];
///// You don't even need to touch this code!!!
var table = $("#searchresults");
(function(){// generate header row
var tr = $('<tr>');
if(data && data.length)
for(var key in data[0])
tr.append("<td class='table-header'>"+key+"</td>");
table.append(tr);
})();
// generate content rows
for (var i = 0; i < 10; i++) {
var tr = $('<tr>');
if(data[i])
for(var key in data[i])
tr.append("<td>" + data[i][key] + "</td>");
else
for(var key in data[0])
tr.append("<td> </td>");
table.append(tr);
}
#searchresults{
border-collapse: collapse;
}
#searchresults td{
border: 1px solid grey;
}
#searchresults .table-header{
border-bottom: 2px solid black;
padding: 3px 5px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="searchresults"></table>

Move Table Rows

I have my table like this, I want to move up and down these rows on click these arrows can anybody help me out ......
function MoveRowDown(tableId, index)
{
var rows = $("#" + tableId + " tr");
rows.eq(index).insertAfter(rows.eq(index + 1));
}
function MoveRowUp(tableId, index)
{
var rows = $("#" + tableId + " tr");
rows.eq(index).insertBefore(rows.eq(index - 1));
}
int ItemSetupID = EBusiness.GetCommonSetupID(this.Data.WFID, EBusiness.CommonSetupID.ItemSetup);
MModules objItemSetupModules = new MModules();
objItemSetupModules.LoadModules(ItemSetupID);
StringBuilder ret = new StringBuilder(4000);
ret.Append("<table class=\"box-table-a\"><tr><td><img id=\"left\" src=\"../../images/downarrow.png\" onclick=\"MoveRowDown(tableId,index);\"></td></tr><tr><td>");
ret.Append("<table id=\"tableId\" class=\"box-table-a\"><tr><th>Items</th></tr>");
int index = 0;
foreach (MModule module in objItemSetupModules.Modules)
{
ret.Append("<tr><td><input type=\"hidden\" name=\"Items" + module.ModuleID + "\" id=\"Items" + module.ModuleID + "\" />");
ret.Append("<tr><td><input type=\"hidden\" name=\"index" + index + "\" id=\"index" + index + "\" />");
ret.Append("<a href=\"#\" class=\"lnkShowFilter\" onclick=\"$('#index" + index + "').val('#index" + index + "'); $('.lnkShowFilter').css('color', '#000000');this.style.color='#FF0000';ShowFilterSaleMargin('" + module.TableName + "', '" + module.Title + "', 'divFilter" + module.ModuleID + "')\">");
ret.Append("" + module.Title + "</a> ");
ret.Append("<input type=\"hidden\" id=\"hidShowFilter" + module.Title + "\" value=\"false\" />");
ret.Append("<div id=\"divFilter" + module.ModuleID + "\" style=\"text-align:left;border:1px SOLID #333333;background-color:White;display:none;position:absolute;\">");
ret.Append("<div id=\"sdivFilter" + module.ModuleID + "\" style=\"border:1px SOLID #EEEEEE;background-color:#AAAABB; width:150px;height:100px;overflow-y:auto;\"></div>");
ret.Append("<input type=\"button\" value=\" OK \" class=\"button\" onclick=\"$('#' + openedDivID).hide();GetItemData('" + module.ModuleID + "', '" + module.Title + "');\" />");
ret.Append("</div></td></tr>");
index++;
}
ret.Append("</table></td><td>");
ret.Append("<table class=\"box-table-a\"><tr><th>Data</th></tr>");
foreach (MModule module in objItemSetupModules.Modules)
{
ret.Append("<tr id=\"tdModule" + module.ModuleID + "\"><td ></td></tr>");
}
ret.Append("</table></td></tr><tr><td><img id=\"left\" src=\"../../images/uparrow.png\" onclick=\"MoveRowUp(tableId, index);\"></td></tr></table>");
this.Output = ret.ToString();
We have to use insertBefore and insertAfter methods of jQuery to insert before and after the dom element respectively.
The sample code is like:
if(e.target.innerHTML == "Up") {
if(index != 0) {
currRow.insertBefore($("tr:eq(" + (index-1) + ")"));
}
} else if(e.target.innerHTML == "Down") {
if(index != (totalTrs-1)) {
currRow.insertAfter($("tr:eq(" + (index+1) + ")"));
}
}
Working DEMO
Source:
Insert After jQuery
Insert Before jQuery
JavaScript-Move Up and Down HTML Table Row: Working Code
function MoveRowDown(tableId)
{
var index=parseInt(document.getElementById("HiddRowindex").value);
var rows = $("#" + tableId + " tr");
table= document.getElementById(tableId);
rowCount = table.rows.length;
if(index+1<rowCount)
{
rows.eq(parseInt(index)).insertAfter(rows.eq(index + 1));
index=(index+1);
document.getElementById("HiddRowindex").value=index;
}
}
function MoveRowUp(tableId)
{
var index=parseInt(document.getElementById("HiddRowindex").value);
var rows = $("#" + tableId + " tr");
table= document.getElementById(tableId);
rowCount = table.rows.length;
if(index-1>0)
{
rows.eq(index).insertBefore(rows.eq(index - 1));
index=(index-1);
document.getElementById("HiddRowindex").value=index;
}
}
///////////////////////////End JavaScript///////////////////////////////
///////////////////////////Code////////////////////////////////////////
int ItemSetupID = EBusiness.GetCommonSetupID(this.Data.WFID,
EBusiness.CommonSetupID.ItemSetup);
MModules objItemSetupModules = new MModules();
objItemSetupModules.LoadModules(ItemSetupID);
StringBuilder ret = new StringBuilder(4000);
ret.Append("<table class=\"box-table-a\"><tr><td><img id=\"left\" src=\"../../images/downarrow.png\" onclick=\"MoveRowDown('tableId');\"></td></tr><tr><td>");
ret.Append("<table id=\"tableId\" class=\"box-table-a\"><tr><th>Items</th><th>Data</th></tr><input type=\"hidden\" name=\"HiddRowindex\" id=\"HiddRowindex\" value=\"\" />");
int index = 1;
foreach (MModule module in objItemSetupModules.Modules)
{
ret.Append("<tr><td><input type=\"hidden\" name=\"Items" + module.ModuleID + "\" id=\"Items" + module.ModuleID + "\" />");
ret.Append("<a href=\"#\" class=\"lnkShowFilter\" onclick=\"$('#HiddRowindex').val($(this).closest('td').parent()[0].sectionRowIndex); $('.lnkShowFilter').css('color', '#000000');this.style.color='#FF0000';ShowFilterSaleMargin('" + module.TableName + "', '" + module.Title + "', 'divFilter" + module.ModuleID + "')\">");
ret.Append("" + module.Title + "</a> ");
ret.Append("<input type=\"hidden\" id=\"hidShowFilter" + module.Title + "\" value=\"false\" />");
ret.Append("<div id=\"divFilter" + module.ModuleID + "\" style=\"text-align:left;border:1px SOLID #333333;background-color:White;display:none;position:absolute;\">");
ret.Append("<div id=\"sdivFilter" + module.ModuleID + "\" style=\"border:1px SOLID #EEEEEE;background-color:#AAAABB; width:150px;height:100px;overflow-y:auto;\"></div>");
ret.Append("<input type=\"button\" value=\" OK \" class=\"button\" onclick=\"$('#' + openedDivID).hide();GetItemData('" + module.ModuleID + "', '" + module.Title + "');\" />");
ret.Append("</div></td>");
ret.Append("<td id=\"tdModule" + module.ModuleID + "\"></td>");
ret.Append("</tr>");
index++;
}
ret.Append("</table></td>");
ret.Append("</tr><tr><td><img id=\"left\" src=\"../../images/uparrow.png\" onclick=\"MoveRowUp('tableId');\"></td></tr></table>");
this.Output = ret.ToString();

How to validate text boxes with in a div javascript or jQuery

how do I integrate a type of validation in my JavaScript to the idea of If value of var firstName is = to null do NOT append the var sHtml and summaryHtml and change the class to change the textbox border and clear the field
rules:
firstName = must contain at least 1 letter and no more than 15 letters
lastName = must contain at least 1 letter and no more than 15 letters
jobTitle = must contain something other than an option value of "" (in the html option tag)
eSculation = must contain something other than an option value of "" (in the html option tag)
mobilePhone = must contain 9 numbers. This field has a mask attached: (999) 999-99999
officePhone = = must contain 9 numbers. This field has a mask attached: (999) 999-99999
eMail = Must contain the following symbol: an # sign and a . to represent xxx#xx.xxx
The JavaScript I am using to submit to a table is below:
newRow = 1;
currentRow = -1;
function CompanyContacts() {
var rowID = parseInt(document.getElementById("ContactsRowCount").value, 10);
rowID++;
if (currentRow > 0) {
saveEdits();
} else {
var firstName = $("#ccFirst").val();
var lastName = $("#ccLast").val();
var jobTitle = $("#ccjTitle").val();
var eSculation = $("#ccEsculation").val();
var mobilePhone = $("#ccMobile").val();
var officePhone = $("#ccOffice").val();
var eMail = $("#ccEmail").val();
var sHtml = "<tr id='row" + rowID + "'>" +
"<td class='tblStyle68wlb' id=\"ccFirst" + rowID + "\">" + firstName + "</td>" +
"<input type=\"hidden\" value=\"" + firstName + "\" name=\"cFirst" + rowID + "\" />" +
"<td class='tblStyle68wl' id=\"ccLast" + rowID + "\">" + lastName + "</td>" +
"<input type=\"hidden\" value=\"" + lastName + "\" name=\"cLast" + rowID + "\" />" +
"<td class='tblStyle68wlb' id=\"ccjTitle" + rowID + "\">" + jobTitle + "</td>" +
"<input type=\"hidden\" value=\"" + jobTitle + "\" name=\"cJobTitle" + rowID + "\" />" +
"<td class='tblStyle68wl' id=\"ccEsculation" + rowID + "\">" + eSculation + "</td>" +
"<input type=\"hidden\" value=\"" + eSculation + "\" name=\"cContactPoint" + rowID + "\" />" +
"<td class='tblStyle68wlb' id=\"ccMobile" + rowID + "\">" + mobilePhone + "</td>" +
"<input type=\"hidden\" value=\"" + mobilePhone + "\" name=\"cMobilePhone" + rowID + "\" />" +
"<td class='tblStyle68wl' id=\"ccOffice" + rowID + "\">" + officePhone + "</td>" +
"<input type=\"hidden\" value=\"" + officePhone + "\" name=\"cOfficePhone" + rowID + "\" />" +
"<td class='tblStyle68wlb' id=\"ccEmail" + rowID + "\">" + eMail + "</td>" +
"<input type='hidden' value='" + eMail + "' name='cEmail" + rowID + "' />" +
"<td class='tblStyle68wl' ><button type='button' class='XsmallButtons' onclick='editRow(" + rowID + ")'>Edit</button>" +
"</td><td class='tblStyle68wlb' ><button type='button' class='XsmallButtons' onclick='deleteRow(" + rowID + ")'>Delete</button>" +
"</td></tr>";
var summaryHtml = "<tr id='SummaryRow" + rowID + "'>" +
"<td id='ccFirst" + rowID + "'>" + firstName + "</td>" +
"<td id='ccLast" + rowID + "'>" + lastName + "</td>" +
"<td id='ccjTitle" + rowID + "'>" + jobTitle + "</td>" +
"<td id='ccEsculation" + rowID + "'>" + eSculation + "</td>" +
"<td id='ccMobile" + rowID + "'>" + mobilePhone + "</td>" +
"<td id='ccOffice" + rowID + "'>" + officePhone + "</td>" +
"<td id='ccEmail" + rowID + "'>" + eMail + "</td>" +
"</tr>";
$("#customerContactSubmitedTable").append(sHtml);
$("#SummaryCCTable").append(summaryHtml);
newRow++;
document.getElementById("ContactsRowCount").value = rowID;
$("#ccFirst,#ccLast,#ccjTitle,#ccEsculation,#ccMobile,#ccOffice,#ccEmail").val("");
}
}
function editRow(rowID) {
$('#ccFirst').val($('#ccFirst' + rowID).html());
$('#ccLast').val($('#ccLast' + rowID).html());
$('#ccjTitle').val($('#ccjTitle' + rowID).html());
$('#ccEsculation').val($('#ccEsculation' + rowID).html());
$('#ccMobile').val($('#ccMobile' + rowID).html());
$('#ccOffice').val($('#ccOffice' + rowID).html());
$('#ccEmail').val($('#ccEmail' + rowID).html());
currentRow = rowID;
}
function saveEdits() {
$('#ccFirst' + currentRow).html($('#ccFirst').val());
$('#ccLast' + currentRow).html($('#ccLast').val());
$('#ccjTitle' + currentRow).html($('#ccjTitle').val());
$('#ccEsculation' + currentRow).html($('#ccEsculation').val());
$('#ccMobile' + currentRow).html($('#ccMobile').val());
$('#ccOffice' + currentRow).html($('#ccOffice').val());
$('#ccEmail' + currentRow).html($('#ccEmail').val());
$("#ccFirst,#ccLast,#ccjTitle,#ccEsculation,#ccMobile,#ccOffice,#ccEmail").val("");
currentRow = -1;
}
function deleteRow(rowID) {
$('#row' + rowID).remove();
$('#SummaryRow' + rowID).remove();
var rowCount = parseInt(document.getElementById("ContactsRowCount").value, 10);
rowCount--;
document.getElementById("ContactsRowCount").value = rowCount;
}
function ccClear() {
$("#ccFirst,#ccLast,#ccjTitle,#ccEsculation,#ccMobile,#ccOffice,#ccEmail").val("");
}
Add a validation="regex here" to the input tags first of all to give them an easy visual notification. Beyond if you want to validate with jQuery, you can check each value and not send out an ajax request if any are invalid, using something like this to verify that ( string in this case ) values are correct $(your_element_here).val().match(your_regex_here)
Perhaps an if ($(#id).val().match(some_verification_regex) == null){ return false }
only letters: /^[A-z]+$/
phone number like you mentioned above: /^\(\d{3}\) \d{3}-\d{4}$/
What i would suggest is a validation jQuery plugin and you can find many of them and choose what suites your needs from bellow:
jquery.bassistance
ddarrenjQuery-Live-Form-Validation-For-Twitter-Bootstrap
jzae fferer-jquery-validation
Or you search on jQuery.com site to get many jquery compatible validation plugins.
But if you don't want to use any plugin then you have to write your own validation code.
Email and other fields validation functions:
function emailValidate(e){
var p = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return p.test(e);
}
function validate(val, min, max){
return (val.length < min || val.length > max?false:true);
}
vfirstName = validate(firstName,1,15);//if between 1 and 15 will return true
vlastName = validate(lastName ,1,15);//if between 1 and 15 will return true
vjobTitle = validate(jobTitle ,1,50);//if between 1 and 15 will return true
veSculation = validate(eSculation ,1,50);//if between 1 and 15 will return true
vmobilePhone = validate(eSculation ,1,50);//if between 1 and 15 will return true
vofficePhone = validate(officePhone,12,12);//because `(999) 999-99999` length is 12
veMail = emailValidate(eMail);//also will return false if wrong email format
if(vfirstName && vlastName && vjobTitle && veSculation && vmobilePhone && vofficePhone && veMail)
var errors = false;
else
var errors = true;
Then before appending the generated row you can add some condition like:
if(!errors){
$("#customerContactSubmitedTable").append(sHtml);
//....rest of your code
}else
alert('please correct the fields');//or any other event

Categories

Resources