Lock Child TR to Parent TR in Javascript - javascript

I'm making a table in Javascript and I can't use my expand row function after using a tablesorter plugin. I can only expand the hidden TRs before using the tablesorter.
I looked it up and it appears I would have to lock the hidden TR child with my parent TR>
My table code is as follows:
$('<tr>').html("<td class='IndicatedDispatch'></td>" + "<td>" + $(this).find("TripID").text() + "</td><td>"
+ $(this).find("RouteNum").text() + "</td><td>"
+ monthArray[theMonth] + " " + $(this).find("ArriveDate").text().substr(8,8).replace("T"," ") + "</td><td>"
+ monthArray[theMonth] + $(this).find("DepartDate").text().substr(8, 8).replace("T", " ") + "</td><td>"
+ $(this).find("CommodityHandle").text() + "</td>").addClass($(this).find("IsDispatched").text() === "0" ? "DispatchNo" : "DispatchYes").appendTo('#dallas');
$('<tr>').html("<td colspan='6'><p>" + $(this).find("DeliverySequence").text() + "</p></td>").hide().appendTo('#dallas');
});
$("#dallas").tablesorter();
setTimeout(function () {
$("tr").click(function (event) {
event.stopPropagation();
var $target = $(event.target);
$target.parent().next().slideToggle();
});
}, 1000);
Basically, how can I expand using my setTimeout function after sorting my table?
Much appreciated.
Tried this and it does not expand at all now:
$('<tr>').html("<td class='IndicatedDispatch'></td>" + "<td>" + $(this).find("TripID").text() + "</td><td>"
+ $(this).find("RouteNum").text() + "</td><td>"
+ monthArray[theMonth] + " " + $(this).find("ArriveDate").text().substr(8,8).replace("T"," ") + "</td><td>"
+ monthArray[theMonth] + $(this).find("DepartDate").text().substr(8, 8).replace("T", " ") + "</td><td>"
+ $(this).find("CommodityHandle").text() + "</td>").addClass($(this).find("IsDispatched").text() === "0" ? "DispatchNo" : "DispatchYes").appendTo('#dallas');
$('<tr data-associatedId="hiddenTr1">').html("<td colspan='6'><p>" + $(this).find("DeliverySequence").text() + "</p></td>").hide().appendTo('#dallas');
});
$("#dallas").tablesorter();
setTimeout(function () {
$("tr").click(function (event) {
event.stopPropagation();
var $target = $(event.target);
$('#' + $target.attr('data-associatedId')).slideToggle();
});
}, 1000);

Related

Append checkbox together with datasnapshot in a table

i want to add checkbox for each and every rows but when i try to run the code, something like this shows "[object HTMLInputElement]" instead of a checkbox
function BSIT(){
$("#stdlist").empty();
var chyear = $('#chyear').val();
$("#showtxt").html(chyear);
var checkbox = document.createElement("INPUT");
checkbox.type = "checkbox";
var ref = firebase.database().ref().child("course/BSIT");
ref.orderByChild("Year").equalTo(chyear).on("child_added", function(snapshot) {
var childData = snapshot.val();
$("#stdlist").append("<tr> <td>" + checkbox + "</td><td>" + childData.StudentId +
"</td><td>" + childData.FirstName +" "+ childData.Lastname +
"</td><td>" + childData.Address +
"</td><td>" + childData.Gender +
"</td><td>" + childData.Age +
"</td><td>" + childData.Phone +
"</td><td>" + childData.Year +
"</td></tr>"
);
});
Output
Try this:
function BSIT(){
$("#stdlist").empty();
var chyear = $('#chyear').val();
$("#showtxt").html(chyear);
var ref = firebase.database().ref().child("course/BSIT");
ref.orderByChild("Year").equalTo(chyear).on("child_added", function(snapshot) {
var childData = snapshot.val();
$("#stdlist").append("<tr> <td>" + '<input type="checkbox">'+ "</td><td>" + childData.StudentId +
"</td><td>" + childData.FirstName +" "+ childData.Lastname +
"</td><td>" + childData.Address +
"</td><td>" + childData.Gender +
"</td><td>" + childData.Age +
"</td><td>" + childData.Phone +
"</td><td>" + childData.Year +
"</td></tr>"
);
});
I hope it will help you :)

How to refresh page so my table does not keep getting added to existing table?

Whenever I click on my button to fire the below query it keeps on appending to the existing table.Is there any way I can refresh the page for every button click.
function submitClick() {
$(document).ready(function () {
const rootRef = firebase.database().ref().child("Orders/");
const query = rootRef.orderByChild('Session').equalTo('VEG');
query.on("child_added", snap => {
var user_id = snap.child("User id").val();
var name = snap.child("Username").val().toUpperCase();
$("#table_body").append("<tr><td>" + user_id + "</td> <td>" + name + "</td> <td>" + email +
"</td><td>" + address + "</td><td>" + dabba_type + "</td><td>" + session + "</td><td>" + start +
"</td><td>" + end + "</td><td>" + phone + "</td><td>" + "Rs " + price + "</td><td>" + feedback + "</td></tr>");
});
});
}
try adding $("#table_body").empty() at the start of the function
create the html into variable and then add to the body
var html = "<tr><td>" + user_id + "</td> <td>" + name + "</td> <td>" + email +
"</td><td>" + address + "</td><td>" + dabba_type + "</td><td>" + session + " </td><td>" + start +
"</td><td>" + end + "</td><td>" + phone + "</td><td>" + "Rs " + price + "</td><td>" + feedback + "</td></tr>";
$("#table_body").html(html);
I can't understand. You can use ajax to reload page or datatables be the best way for refreshing table with out page reload. If you want just reload page then use
location.reload();

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

Why doesn't the code enter each block?

I need to select all the check boxes, that are checked and then get the value of id attribute.
I am doing the following way :
$("input:checkbox[class=selectioncheckbox]").each(function() {
console.log("Inside each block");
if($(this).is(":checked")) {
console.log("Inside if block");
pnames[c] = $(this).attr('id');
console.log(pnames[c] + " " + c);
c++;
}
});
But there is a problem. The code never enters the each block. What could be the reason for this?
EDIT:
Here is the code that adds checkboxes with class selectioncheckbox:
$('#teamcheckbox_a').change(function() {
if($(this).is(':checked')) {
$('#teamcheckbox_b').prop('checked',false);
$('#playerselect').empty();
team_a = $('#teamnames_a option:selected').text();
$.ajax( {
url : 'http://localhost:8081/Football/GetPlayerNames',
data : {
teamname : $('#teamnames_a option:selected').text()
},
dataType : 'json',
type : 'GET'
})
.done(function(message) {
$('#playerselect').html("<label>Select Players</label>");
$.each(message,function(index,row) {
$('#playerselect').append(
"<tr>" +
"<td class='text-center'>" + row.jnumber + "</td>" +
"<td>" + row.name + "</td>" +
"<td class='text-center'>" + row.position + "</td>" +
"<td> <input type='checkbox' class='selectioncheckbox form-control input-lg' id='" + row.jnumber + ":" + row.name + "' /> </td>" +
"</tr>");
});
$('.selectioncheckbox').change(function() {
if($(this).is(':checked')) {
count++;
} else {
count--;
}
$('#pcount').html("Count : " + count);
});
})
.fail(function(message) {
console.log(message);
})
}
});
$('#teamcheckbox_b').change(function() {
if($(this).is(':checked') ) {
$('#teamcheckbox_a').prop('checked',false);
$('#playerselect').empty();
team_a = $('#teamnames_b option:selected').text();
$.ajax( {
url : 'http://localhost:8081/Football/GetPlayerNames',
data : {
teamname : $('#teamnames_b option:selected').text()
},
dataType : 'json',
type : 'GET'
})
.done(function(message) {
$('#playerselect').html("<label>Select Players</label>");
$.each(message,function(index,row) {
$('#playerselect').append(
"<tr>" +
"<td class='text-center'>" + row.jnumber + "</td>" +
"<td>" + row.name + "</td>" +
"<td class='text-center'>" + row.position + "</td>" +
"<td> <input type='checkbox' class='selectioncheckbox form-control input-lg' id='" + row.jnumber + ":" + row.name + "' /> </td>" +
"</tr>");
});
$('.selectioncheckbox').change(function() {
if($(this).is(':checked')) {
count++;
} else {
count--;
}
$('#pcount').html("Count : " + count);
});
})
.fail(function(message) {
console.log(message);
})
}
});
Either the code isn't being called at all, or $("input:checkbox[class=selectioncheckbox]") has a length of 0 (which is most likely caused by running the code before the elements have been added to the DOM, in which case you can resolve it with a ready handler).
Use as selector: $(".selectioncheckbox:checked") because i guess selectioncheckbox is only applied to checkboxes and no need to check for checked state inside each loop.
And your issue was none element was matched because using attribute selector [class=selectioncheckbox] if more than one class set on same element, this doesn't match.
The script is calling before the elements added to the DOM. So the script is unable to identify the class name and the length will be 0. Call the script in the ready handler as follows.
$(document).ready(function(){
var c= 0;
var pnames = [];
$("input:checkbox[class=selectioncheckbox]").each(function() {
console.log("Inside each block");
if($(this).is(":checked")) {
console.log("Inside if block");
pnames[c] = $(this).attr('id');
console.log(pnames[c] + " " + c);
c++;
}
});
});

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