How to disable checkbox if condition is true using jQuery? - javascript

I have tried to disable checkbox like
var t8 =283.50;
var t9 = 283.50;
if (t8 == t9) {
$('.checkBoxClass:input([value=' + t11 + ')').attr('disabled', true);
}
Condition is working but the checkbox is not getting disabled.
trtoggle +=
"<tr><td class='invoicedate_check'>" + t6 +
"</td><td class='invoiceno_check'>" + t7 +
"</td><td style='text-align: right;' class='invoiceamt_check'>" + t8 +
"</td><td style='text-align: right;' class=''>" + t9 +
"</td><td style='text-align: right;' class=''>" + balance +
"</td><td class='checkBoxtd" + t11 +
"'><input type='checkbox' class='checkBoxClass checkBoxClassse" + t11 +
"' id='checkbox"+t11+"' name='myTextEditBox[]' value='" + t11 +
"'/> Select</td></tr>";
$(".tableinvoice_proj").last().append(trtoggle);
Here is my full function code:
$('#projectname_add').on('change', function() {
$(".projectname_add_TextBox").val($(".projectname_add option:selected").html());
var projectname_add = $('.projectname_add').val();
var getID_comp = $('#getID_comp').val();
//alert(getID_comp)
$('#tableproject').find('tbody').remove();
$('#tableinvoice_proj').find('tbody').remove();
$('#myprojdisplay_new').find('tbody').remove();
$('#myprojdisplaylatest').find('tbody').remove();
if(projectname_add !== "list_all_projects"){
$.ajax({
url: base_url + "index.php/welcome/list_a_projects_invoice/",
// url: base_url + "index.php/welcome/invoice_allList/",
type: "POST",
data: {
"id": projectname_add
},
success: function(data) {
var new_data = JSON.parse(data);
console.log(new_data)
if(new_data == "No Records Found"){ //no invoice for this project
$('#myprojdisplay_new').hide();
$('#tableproject').hide();
$('#myprojdisplaylatest').hide();
}else{
$('#myprojdisplay_new').show();
$('#myprojdisplaylatest').show();
$('#tableproject').show();
}
for (var i = 0; i < new_data.projectinvoicesection.length; i++) {
var sl = i +1;
//alert(t6)
var t1 = new_data.projectinvoicesection[i]['parent'].project_amount;
var t2 = new_data.projectinvoicesection[i]['parent'].particulars;
var t3 = new_data.projectinvoicesection[i]['parent'].project_ID;
var t4 = new_data.projectinvoicesection[i]['parent'].project_title;
var t5 = new_data.projectinvoicesection[i]['parent'].type;
var t56 = new_data.projectinvoicesection[i]['parent'].period_type;
var object = new_data.projectinvoicesection[i]['child'];
var tr = "<tr data-toggle='collapse' data-target='#demo" + t3 + "' style='background-color: #BBDDDD;color: black;' class='accordion-toggle'><td>"+ sl+"</td><td>"+ t4+"</td><td style='text-align: right;'>"+t1+"</td><td style='white-space: nowrap;'>" + t5 + " " + t56 + "</td><td><button class='open-button-project-edit btn' data-toggle='modal' data-backdrop='static' data-keyboard='false' data-target='#exampleModal_2' onclick='openForm3(" + t3 + ")' style='color: #fff;background-color: #398439;border-color: #255625;'>EDIT</button></td></tr><tr><td colspan='6' class='hiddenRow'><div class='accordian-bodyproj collapse' id='demo" + t3 + "'> <table id='tableinvoice_proj' class='tableinvoice_proj' style='font-size: 14px; border-collapse:collapse;width: 745px; table-layout: fixed;'><thead style='background-color: #86af49;'><tr><th>Invoice Date</th><th>Invoice Number</th><th>Invoice Amount</th><th>Received Amount</th><th>Balance</th><th>Generate Receipt</th></tr></thead><tbody></tbody></table>";
$("#tableproject").append(tr);
$("#tableproject").append('</div></td></tr>');
if( !object || object.length < 1)
{
var trtoggle = `<tr ><td style='text-align:center;' colspan='6' > No records found!</td></tr>`;
} else
{
var trtoggle = '';
for (var property in object) {
var t6 = format(object[property].invoice_date);
var t7 = object[property].invoice_no;
var t8 = object[property].invoice_amount;
//var t9 = object[property].received_Amt;
var t9 = object[property].totalreceiptamt; //received amount
var t11 = object[property].invoice_ID;
var t10 = object[property].proje_ID; //invoice table's project id
if (t9 == '0.00'){
var receiveornot = 'Yet to receive';
var balance = object[property].invoice_amount;
}
else{
var receiveornot = object[property].totalreceiptamt;
var balance = parseFloat(object[property].invoice_amount - object[property].totalreceiptamt).toFixed(2);
}
// trtoggle += "<tr><td class='invoicedate_check'>" + t6 + "</td><td class='invoiceno_check'>" + t7 + "</td><td style='text-align: right;' class='invoiceamt_check'>" + t8 + "</td><td style='text-align: right;' class=''>" + t9 + "</td><td style='text-align: right;' class=''>" + balance + "</td><td class='checkBoxtd" + t11 + "'><input type='checkbox' class='checkBoxClass checkBoxClassse" + t11 + "' id='checkbox"+t11+"' name='myTextEditBox[]' value='" + t11 + "'/> Select</td></tr>";
trtoggle +=
"<tr><td class='invoicedate_check'>" + t6 +
"</td><td class='invoiceno_check'>" + t7 +
"</td><td style='text-align: right;' class='invoiceamt_check'>" + t8 +
"</td><td style='text-align: right;' class=''>" + t9 +
"</td><td style='text-align: right;' class=''>" + balance +
"</td><td class='checkBoxtd" + t11 +
"'><input type='checkbox' class='checkBoxClass checkBoxClassse" + t11 +
"' id='checkbox"+t11+"' name='myTextEditBox[]' value='" + t11 +
"'/> Select</td></tr>";
if (t8 == t9) {
console.log("---");
// console.log($('.checkBoxClass:input([value=' + t11 + '])'));
$('.checkBoxClass:input([value=' + t11 + '])').prop('disabled', true);
}
}
}
$(".tableinvoice_proj").last().append(trtoggle);
}
}
});
}
})
The above is the code when dropdown option changed, two tables are displaying.one table for project details inside project details invoice html table will come.Here i need to disable the checkbox based on the if condition

you can add attribute in html like this because you are appending html after your jquery code
$('#projectname_add').on('change', function() {
$(".projectname_add_TextBox").val($(".projectname_add option:selected").html());
var projectname_add = $('.projectname_add').val();
var getID_comp = $('#getID_comp').val();
//alert(getID_comp)
$('#tableproject').find('tbody').remove();
$('#tableinvoice_proj').find('tbody').remove();
$('#myprojdisplay_new').find('tbody').remove();
$('#myprojdisplaylatest').find('tbody').remove();
if(projectname_add !== "list_all_projects"){
$.ajax({
url: base_url + "index.php/welcome/list_a_projects_invoice/",
// url: base_url + "index.php/welcome/invoice_allList/",
type: "POST",
data: {
"id": projectname_add
},
success: function(data) {
var new_data = JSON.parse(data);
console.log(new_data)
if(new_data == "No Records Found"){ //no invoice for this project
$('#myprojdisplay_new').hide();
$('#tableproject').hide();
$('#myprojdisplaylatest').hide();
}else{
$('#myprojdisplay_new').show();
$('#myprojdisplaylatest').show();
$('#tableproject').show();
}
for (var i = 0; i < new_data.projectinvoicesection.length; i++) {
var sl = i +1;
//alert(t6)
var t1 = new_data.projectinvoicesection[i]['parent'].project_amount;
var t2 = new_data.projectinvoicesection[i]['parent'].particulars;
var t3 = new_data.projectinvoicesection[i]['parent'].project_ID;
var t4 = new_data.projectinvoicesection[i]['parent'].project_title;
var t5 = new_data.projectinvoicesection[i]['parent'].type;
var t56 = new_data.projectinvoicesection[i]['parent'].period_type;
var object = new_data.projectinvoicesection[i]['child'];
var tr = "<tr data-toggle='collapse' data-target='#demo" + t3 + "' style='background-color: #BBDDDD;color: black;' class='accordion-toggle'><td>"+ sl+"</td><td>"+ t4+"</td><td style='text-align: right;'>"+t1+"</td><td style='white-space: nowrap;'>" + t5 + " " + t56 + "</td><td><button class='open-button-project-edit btn' data-toggle='modal' data-backdrop='static' data-keyboard='false' data-target='#exampleModal_2' onclick='openForm3(" + t3 + ")' style='color: #fff;background-color: #398439;border-color: #255625;'>EDIT</button></td></tr><tr><td colspan='6' class='hiddenRow'><div class='accordian-bodyproj collapse' id='demo" + t3 + "'> <table id='tableinvoice_proj' class='tableinvoice_proj' style='font-size: 14px; border-collapse:collapse;width: 745px; table-layout: fixed;'><thead style='background-color: #86af49;'><tr><th>Invoice Date</th><th>Invoice Number</th><th>Invoice Amount</th><th>Received Amount</th><th>Balance</th><th>Generate Receipt</th></tr></thead><tbody></tbody></table>";
$("#tableproject").append(tr);
$("#tableproject").append('</div></td></tr>');
if( !object || object.length < 1)
{
var trtoggle = `<tr ><td style='text-align:center;' colspan='6' > No records found!</td></tr>`;
} else
{
var trtoggle = '';
for (var property in object) {
var t6 = format(object[property].invoice_date);
var t7 = object[property].invoice_no;
var t8 = object[property].invoice_amount;
//var t9 = object[property].received_Amt;
var t9 = object[property].totalreceiptamt; //received amount
var t11 = object[property].invoice_ID;
var t10 = object[property].proje_ID; //invoice table's project id
if (t9 == '0.00'){
var receiveornot = 'Yet to receive';
var balance = object[property].invoice_amount;
}
else{
var receiveornot = object[property].totalreceiptamt;
var balance = parseFloat(object[property].invoice_amount - object[property].totalreceiptamt).toFixed(2);
}
// trtoggle += "<tr><td class='invoicedate_check'>" + t6 + "</td><td class='invoiceno_check'>" + t7 + "</td><td style='text-align: right;' class='invoiceamt_check'>" + t8 + "</td><td style='text-align: right;' class=''>" + t9 + "</td><td style='text-align: right;' class=''>" + balance + "</td><td class='checkBoxtd" + t11 + "'><input type='checkbox' class='checkBoxClass checkBoxClassse" + t11 + "' id='checkbox"+t11+"' name='myTextEditBox[]' value='" + t11 + "'/> Select</td></tr>";
var disabled = "";
if (t8 == t9) {
disabled = "disabled";
}
trtoggle += "<tr><td class='invoicedate_check'>" + t6 + "</td><td class='invoiceno_check'>" + t7 + "</td><td style='text-align: right;' class='invoiceamt_check'>" + t8 + "</td><td style='text-align: right;' class=''>" + receiveornot + "</td><td style='text-align: right;' class=''>" + balance + "</td><td class='checkBoxtd" + t11 + "'><input type='checkbox' class='checkBoxClass checkBoxClassse" + t11 + "' id='checkbox"+t11+"' name='myTextEditBox[]' "+disabled+" value='" + t11 + "'/> Select</td></tr>";
}
}
$(".tableinvoice_proj").last().append(trtoggle);
}
}
});
}
})

Related

Dynamically number of buttons after ajax call

I have to dynamically create buttons in an Ajax success function. There isn't a fixed number of buttons and
each time the number is different.
I can do it, but not knowing the exact number of elements that will be created, I don't know how to add the correct number of button listener.
AJAX:
success : function(data, status, xhr) {
$("#risultatoLibriCercati").empty();
var divContent = "";
for (var i = 0; i < data.length; i++) {
divContent +=
"<div class='col-sm-2 mt-4'><a data-toggle='modal' data-target='#bookPage" +
[i] +
"'><div class='card shadow-sm'><img style='height:250px' src='" +
data[i].imgLink +
"' class='img-thumbnail rounded'></div></a></div><div class='modal fade' id='bookPage" +
[i] +
"'><div class='modal-dialog'><div class='modal-content'><div class='modal-header text-center'><h4 class='modal-title w-100 dark-grey-text font-weight-bold'>" +
data[i].titolo +
"</h4><button type='button' class='close' data-dismiss='modal' aria-lable='close'>×</button></div><div class='mt-4' style='background: url(" +
data[i].imgLink +
") no-repeat;background-size: contain; background-position: center; min-height: 300px;'></div><div class='modal-body mx-4'><div class='md-form'><p class='font-small'>" +
data[i].autore +
"</p></div><div class='md-form'><p>" +
data[i].descrizione +
"</p></div><div class='text-center mb-3'><button class='btn btn-primary btn-block z-depth-1a' id='aggiungi" +
[i] +
"'>Aggiungi a libreria</button><a href='" +
data[i].isbn13.replace("'", " ") +
"' target='_blank' style='border:none;text-decoration:none'><img src='https://www.niftybuttons.com/amazon/amazon-button2.png'></a></div></div></div></div></div><input type='hidden' id='categoria" +
[i] +
"' value='" +
data[i].categoria +
"'><input type='hidden' id='googleID" +
[i] +
"' value='" +
data[i].googleID +
"'><input type='hidden' id='titolo" +
[i] +
"' value='" +
data[i].titolo.replace("'", " ") +
"'><input type='hidden' id='descrizione" +
[i] +
"' value='" +
data[i].descrizione.replace("'", " ") +
"'><input type='hidden' id='autore" +
[i] +
"' value='" +
data[i].autore +
"'><input type='hidden' id='isbn" +
[i] +
"' value='" +
data[i].isbn13.replace("'", " ") +
"'><input type='hidden' id='voto" +
[i] +
"' value='" +
data[i].voto +
"'><input type='hidden' id='imgLink" +
[i] +
"' value='" +
data[i].imgLink +
"'>";
}
$("#risultatoLibriCercati").append(divContent);
}
BUTTON ON CLICK LISTENER:
$(document).on('click', '#aggiungi0', function(){
var book = {
googleID: $("#googleID0").val(),
titolo: $("#titolo0").val(),
descrizione: $("#descrizione0").val(),
isbn13: $("#isbn0").val(),
voto: $("#voto0").val(),
imgLink: $("#imgLink0").val(),
autore: $("#autore0").val(),
categoria: $("#categoria0").val(),
userId: getCookie("userId"),
};
$.ajax({
[...]
You can add class attribute for those buttons and attach event and index for them as below
var btnIndex = 0;
$('#add').on('click', function() {
$('.container').append(`<button class="new-btn" data-index=${btnIndex++}>Button test</button>`);
});
$('.container').on('click', '.new-btn', function(e) {
console.log("clicked" + $(e.target).data("index"));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Add</button>
<div class="container"></div>
And passing these values by index into ajax call like this:
$(document).on('click', '.new-btn', function(e){
const idx = $(e.target).data("index");
var book = {
googleID: $("#googleID" + idx).val(),
titolo: $("#titolo" + idx).val(),
descrizione: $("#descrizione" + idx).val(),
isbn13: $("#isbn" + idx).val(),
voto: $("#voto" + idx).val(),
imgLink: $("#imgLink0" + idx).val(),
autore: $("#autore" + idx).val(),
categoria: $("#categoria" + idx).val(),
userId: getCookie("userId"),
};
$.ajax({
[...]

How can I get text value from modal with javascript?

I'm fetching the values from my table in ajax.
$(data.mesIzinTanimList).each(function (index, element) {
if (element.izinTanimiVarmi == 'yok')
tr = "<tr class='bg-warning text-warning-50' row='" + element.userId + "' >";
else
tr = "<tr class='bg-light text-white-50 ' row='" + element.userId + "' >";
tr += "<td>" + element.sicilNo + "</td>";
tr += "<td>" + element.adSoyad + "</td>";
tr += "<td>" + element.bagliOlduguKisi + "</td>";
tr += "<td>" + element.bagliOlduguKisiSicilNo + "</td>";
tr += "<td style='display:none'>" + element.bagliOlduguKisiId + "</td>";
tr += "<td> <button onclick= 'tanimlaBtn(" + element.userId + " , " + element.adiSoyadi + " ," + element.bagliOlduguKisiId + ", " + element.bagliOlduguKisi + ")' type='button' class ='btn btn-info'> Tanımla </button></td>";
tr += "</tr>";
$('#IzinTanimListe').append(tr);
});
I open a modal with the define Btn onclick feature.
function tanimlaBtn(userId, adSoyad, bagliOlduguKisiId, bagliOlduguKisi) {
document.getElementById('userId').value = userId;
document.getElementById('bagliOlduguKisiId').value = bagliOlduguKisiId;
document.getElementById('bagliOlduguKisi').value = bagliOlduguKisi;
document.getElementById('adSoyad').value = adSoyad;
}
The adSoyad and bagliOlduguKisi information appears as undefined. They should be string values.
How can I solve this?
The parameters for the function should be wrapped in doubles quotes and escaped e.g \"
Try replacing:
<button onclick= 'tanimlaBtn(" + element.userId + " , " + element.adiSoyadi + " ," + element.bagliOlduguKisiId + ", " + element.bagliOlduguKisi + ")'
With:
<button onclick='tanimlaBtn(" + element.userId + " , " + element.adiSoyadi + " ,\"" + element.bagliOlduguKisiId + "\", \"" + element.bagliOlduguKisi + "\")'

how to check equality between and array and html table value

I check the equality between an array value and html table cell value both are same but how can i check this. I try this but it wont work properly. it always return true if there are same value. check this out.......
function addOrder() {
var bookid = document.getElementById("book_id").value;
var qty = document.getElementById("qty").value;
var price = document.getElementById("unit_price").value;
var total = document.getElementById("dts_total_price").value;
var table = document.getElementById("results");
var tableData = new Array();
$('#results tr').each(function() {
var row = $(this);
tableData.push(row.find("TD").eq(0).html());
});
tableData.shift();
var check;
for (var i = 0; i <= tableData.length; i++) {
var booksId = tableData[i];
alert(bookid);
if (bookid === booksId) {
check = false;
} else {
check = true;
}
}
alert(check);
var table_len = (table.rows.length);
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'>" +
"<td id='book_row" + table_len + "'>" + bookid + "</td>" +
"<td id='qty_row" + table_len + "'>" + qty + "</td>" +
"<td id='price_row" + table_len + "'>" + price + "</td>" +
"<td id='total_row" + table_len + "'>" + total + "</td>" +
"<td><input type='button' id='edit_button" + table_len + "' value='Edit' class='edit' onclick='edit_row(" + table_len + ")'>" +
" <input type='button' id='save_button" + table_len + "' value='Save' class='save' onclick='save_row(" + table_len + ")'> " +
"<input type='button' value='Delete' class='delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("qty").value = "";
document.getElementById("unit_price").value = "";
document.getElementById("dts_total_price").value = "";
};

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