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
Related
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);
}
I'm trying to nest 3 divs within a "row" div.
I had this working in "long format" (multiple var's instead of looping through the array). I've refactored my code and now I don't get any error codes AND my code does not append to the HTML file. When I console log I get an array with 3 objects. I'm sure i'm missing something minor.
Anyways some help would be great!
<div class="row">
**nested divs go here.
</div>
$(document).ready(function() {
$.get("http://api.openweathermap.org/data/2.5/forecast/daily?id4726206&cnt=3", {
APPID: "MY API KEY",
lat: 29.423017,
lon: -98.48527,
units: "imperial"
}).done(function(data) {
var stationId = data.city.name;
// Stattion Name
$('#station').append(stationId);
//console.log(data);
var forecast = data.list;
//Wind Direction in Compass Format
function getDirection(dir) {
var compass = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
var result = Math.floor((360 - dir) / 22.5);
return compass[result];
}
//Forecast Variables
$.each(forecast, function(i, v) {
var html = '';
html += "<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>";
html += "<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°';
html += " / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>";
html += "<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon;
html += ".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main;
html += "</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>";
html += "<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>";
html += "<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed));
html += " mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>";
html += "<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div>";
return html;
});
$('.forecast').append(forecast);
console.log(forecast);
});
});
You are trying to append the array forecast in html. which wont work. You should declare the html variable outside and then use it in append function.
I will also recommend to use string builder logic using array and then convert it to string and append it. remember string concatenation is heavy operator as it creates new instance of elememt every time concatenation is done :
var html = [];
$.each(forecast, function(i, v) {
html.push("<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>");
html.push("<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°');
html.push(" / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>");
html.push("<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon);
html.push(".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main);
html.push("</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>");
html.push("<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>");
html.push("<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed)));
html.push(" mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>");
html.push("<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div></div>");
});
$('.forecast').append(html.join(""));
$("#searchresult").append("<tr><td id=''>" + data[i].landarp + "</td>" + "<td id=''>" + data[i].landarp + "</td>" + "<td id=''>" + data[i].landpin + "</td>" + "<td id=''>" + (data[i].landlot ? "Lot " + data[i].landlot : "") + "/" + (data[i].landblock ? "Block " + data[i].landblock : "") + "</td>" + "<td id=''>" + data[i].landfirstname + " " + data[i].landmiddlename + " " + data[i].landlastname + ", " + data[i].landsuffix + "</td>"
for (var land = 0; land < landaddress.length; land++) {
landownercontactflag = landaddress[land].landownercontactflag;
landownercontactflag === "1" ? (contactaddress = landaddress[land].landownerprovince + " " + landaddress[land].landownermunicipality + " " + landaddress[land].landownerbarangay + ", " + landaddress[land].landownerstreet) : (homeaddress = landaddress[land].landownerprovince + " " + landaddress[land].landownermunicipality + " " + landaddress[land].landownerbarangay + ", " + landaddress[land].landownerstreet) + "<td id=''>" + landownercontactflag === "1" ? contactaddress : homeaddress + "</td>"
} + "<td id=''>" + data[i].landyear + "</td>" + "<td id=''>" + "<a class=\"af_rpta_treasuryall_specificpin\" id=" + data[i].landpin + " href='#' >View Details</a>" + "</td></tr>");
Trying to append data from database using this code but then i get Uncaught SyntaxError: missing ) after argument list in this line +"<td id=''>" + data[i].landfirstname + " " + data[i].landmiddlename + " " + data[i].landlastname + ", " + data[i].landsuffix + "</td>" what is the cause of this and how to fix it
If you remove all the data specific parts, this is what you have:
$("#searchresult").append("text"
for (var land = 0; land < landaddress.length; land++) {
landownercontactflag = "text";
}
+ "text");
I am not missing a ")" i checked it thoroughly i think its because of for loop inside append just like comment above
There's a missing ")" at the end of the append("text"
(you'll also notice I've changed the indentation to how it's interpreted)
Javascript does not require the use of ";" to end statements and you can use a newline to mean the same, ie these are equivalent:
$("#").append()
and
$("#").append();
because there's a newline at the end of the append(, it looks to see what the next statement is. If this was a '+' it would continue to append the next text, but in this case, it's a new statement for - so javascript attempts to close off the .append( and gives an error that there's a missing ")".
This is the equivalent of:
$("#searchresult").append("text";
for ...
see the ";" at the end now? As there's no ")" before the implied ";", it gives you the warning that there's a ")" missing.
If you did add the ');' at the end of the line then you'll get an error later on about the + .. as there's nothing for the + to be +ed to.
As you've established, this is because of trying to put a command inside the brackets of another - but I wanted to explain why the interpreter thinks this way with the implied end-of-statement at a newline.
You can't put a for statement inside a $("#searchresult").append(
My suggestion is to create a variable and to populate it... then to use it inside append.
For example:
var myVar = "<tr><td id=''>" + data[i].landarp + "</td>" + "<td id=''>" + data[i].landarp
...
for (var land = 0; land < landaddress.length; land++) {
landownercontactflag = landaddress[land].landownercontactflag;
....
myVar = myVar + ......
.....
}
....
$("#searchresult").append(myVar);
But... are you sure you really know what your "for" loop is doing?
UPDATE: as alternative (without a variable):
$("#searchresult").append("<tr><td id=''>" + data[i].landarp + "</td>" + "<td id=''>" + data[i].landarp ....);
...
for (var land = 0; land < landaddress.length; land++) {
landownercontactflag = landaddress[land].landownercontactflag;
....
$("#searchresult").append(".....");
}
....
$("#searchresult").append("....");
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 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