How to compare the multiple dropdown box values using Javascript/jQuery? - javascript

I am having 3 dropdown list which contains the expressions for filtering the datatables based on their selection, for example,
<select class="AssetSearch" title="ASSET_TYPE">
<option value="0">--Select Asset Type--</option>
<option value="PC">PC</option>
<option value="Workstation">Workstation</option>
</select>
<select class="AssetSearch" title="Location_code">
<option value="0">--Select Location--</option>
<option value="Bldg 1">Bldg 1</option>
<option value="Bldg A1">Bldg A1</option>
</select>
<select class="AssetSearch" title="FLOOR_NO">
<option value="0">--Select Floor No--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button class="btnSearchAsset" value="search">Search
</button>
<table id="dataTable">
<thead>
<tr>
<th>Asset Type</th>
<th>Location</th>
<th>Floor No</th>
</tr>
</thead>
<tbody>
<tr>
<td>Printer</td>
<td>Bldg 1</td>
<td>2</td>
</tr>
<tr>
<td>Telephone</td>
<td>Bldg A1</td>
<td>1</td>
</tr>
<tr>
<td>Telephone</td>
<td>Bldg A1</td>
<td>2</td>
</tr>
<tr>
<td>Telephone</td>
<td>Bldg A1</td>
<td>3</td>
</tr>
<tr>
<td>Printer</td>
<td>Bldg A1</td>
<td>3</td>
</tr>
</tbody>
</table>
<script>
$('document').ready(function() {
var assetTypeSel, locSel, floorNoSel;
var queryDBStr;
$("select[title = 'Location_code']").on("change", function() {
$(this).attr("selected", "selected");
//alert($(this).val());
locSel = $(this).val();
});
$("select[title = 'ASSET_TYPE']").on("change", function() {
assetTypeSel = $(this).val();
});
$("select[title = 'FLOOR_NO']").on("change", function() {
floorNoSel = $(this).val();
});
$(".btnSearchAsset").on("click", function(evt) {
var selVal = [];
if ((assetTypeSel == 0) && (locSel == 0) && (floorNoSel == 0)) {
alert("Please Select atleast one option from any of the dropboxes");
} else {
$.each($("select.AssetSearch").children("option").filter(":selected"), function() {
selVal.push($(this).val());
});
for (var i = 0; i < selVal.length; i++) {
if (selVal[i] != 0) {
queryDBStr = "b.ASSET_TYPE = #" + selVal[0] + "# AND c.LOCATION_CODE = #" + selVal[1] + "# AND b.FLOOR_NO = " + selVal[2] + " ";
alert(queryDBStr);
} else if ((selVal[0] == 0) && ((selVal[1] != 0) && (selVal[2] != 0))) {
queryDBStr = "c.LOCATION_CODE = #" + selVal[1] + "# AND b.FLOOR_NO = " + selVal[2] + " ";
alert(queryDBStr);
} else if ((selVal[0] != 0) && ((selVal[1] != 0) && (selVal[2] == 0))) {
queryDBStr = "b.ASSET_TYPE = #" + selVal[0] + "# AND c.LOCATION_CODE = " + selVal[1] + " ";
}
//Further other else if ladders to follow :( - # codes before and after the double quotes(") symbol is to replace it with single quotes (') in the webmethod
}
AssetReportFill(queryDBStr); //Function for ajax call and change the table according to the filters from the db
}
});
});
</script>
Now, the user can select the values from the dropdown in any type of combinations, like, dropbox1 - selected value + dropbox2 - selected value or dropbox 1 - selected value only or all 3 dropboxes selected etc, etc.... then the #dataTable should only show the elements as per the selected values in the dropdown.
Can any one please tell me some effective way to compare all these possible combinations using jQuery or Javascript and pass the query string based on given filter condition to the server and change the datatable accordingly.
JsFiddle link: https://jsfiddle.net/zapkingdude/cowfwerj/

Provide an id for each of the dropdownList and then get the value at the particular dropdown using:
value = document.getElementById("id-of-the-dropbox").val;
Then make a request to the server by making an jSON data.
call a function on change of the dropdown selection as
onchange = "function ()"

Related

Why is there 5 elements being created in my list? Need to create tally function. JavaScript

The main focus is within the JS, the 'add appointment' function is looping and the 'years' value ends up with a list of 5 elements even though only one appointnment is being made. I think two extra's are being created from the add appointment function, and another 2 are being created from the concurrent appointment function. This is for a group project, and i didn't do this component which is why im struggling to understand and fix this problem.
Im trying to push the yy variable into the years list, then create a tally function to list how many appointments are in each year.
Any advice is highly appreciated! and if I haven't elaborated enough please let me know! :)
Thanks in advance
<html>
<head>
<script>
const MIN_YEAR = 2019;
var years = [];
var list = [];
let appointment = {
date: "",
startTime: "",
endTime: "",
subject: "",
venue: "",
rowData: function () {
return "<tr><td>" + this.date + "</td><td>" + this.startTime + "</td><td>" + this.endTime + "</td><td>" + this.subject + "</td><td>" + this.venue + "</td><td>" + this.priority + "</td></tr>";
}
}
function addAppointment() {
let newAppointment = Object.create(appointment);
var startIndex = document.getElementById('startTime').selectedIndex;
var priority;
newAppointment.startTime = document.getElementById('startTime').options[startIndex].value;
newAppointment.subject = document.getElementById('subject').value;
newAppointment.venue = document.getElementById('venue').value;
if (validDate() != false) { newAppointment.date = validDate(); }
if (validTime != false) { newAppointment.endTime = validTime(); }
if (document.getElementById('medium').checked) { priority = medium.value; }
else if (document.getElementById('low').checked) { priority = low.value; }
else { priority = high.value; }
newAppointment.priority = priority;
if (validDate() === null | validDate() === undefined | validTime() === null | validTime() === undefined | validTime() === false | validDate() === false | isConcurrentAppointment(newAppointment.date, newAppointment.startTime, newAppointment.endTime) != true) {
alert('Date or time entry invalid')
}
else {
list.push(newAppointment);
let tbody = document.getElementById("tbody");
tbody.innerHTML += newAppointment.rowData();
}
}
function validDate() {
var inputDate = document.getElementById('date').value
var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
if (inputDate.match(dateformat)) {
document.getElementById('date').focus();
var opera1 = inputDate.split('/');
var opera2 = inputDate.split('-');
lopera1 = opera1.length;
lopera2 = opera2.length;
if (lopera1 > 1) {
var pdate = inputDate.split('/');
}
else if (lopera2 > 1) {
var pdate = inputDate.split('-');
}
var dd = parseInt(pdate[0]);
var mm = parseInt(pdate[1]);
var yy = parseInt(pdate[2]);
years.push(yy);
if (yy < MIN_YEAR) {
alert('Date is invalid.');
return error;
}
var daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (mm == 1 || mm > 2) {
if (dd > daysInMonths[mm - 1]) {
alert('Date is invalid.');
return error;
}
}
if (mm == 2) {
var lyear = false;
if ((!(yy % 4) && yy % 100) || !(yy % 400)) {
lyear = true;
}
if ((lyear == false) && (dd >= 29)) {
alert('Date is invalid');
return error;
}
if ((lyear == true) && (dd > 29)) {
alert('Date is invalid.');
return error;
}
}
}
else {
alert('Date is invalid.');
document.getElementById('date').focus();
return error;
}
return inputDate;
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function validTime() {
var startIndex = document.getElementById('startTime').selectedIndex;
var appStartTime = document.getElementById('startTime').options[startIndex].value;
var endIndex = document.getElementById('endTime').selectedIndex;
var endTime = document.getElementById('endTime').options[endIndex].value;
if (endTime <= appStartTime) {
alert("Appointment must end later than the start time.");
return error;
}
return endTime;
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function isConcurrentAppointment(dateInput, startInput, endInput) {
var i;
for (i = 0; i < list.length; i++) {
if (dateInput == list[i].date) {
if (startInput.substring(0, 3) == list[i].startTime.substring(0, 3)
|| startInput.substring(0, 3) < list[i].startTime.substring(0, 3) && endInput.substring(0, 3) > list[i].endTime.substring(0, 3)
|| startInput.substring(0, 3) == list[i].startTime.substring(0, 3) && endInput.substring(0, 3) >= list[i].endTime.substring(0, 3)
|| startInput.substring(0, 3) > list[i].startTime.substring(0, 3) && endInput.substring(0, 3) > list[i].endTime.substring(0, 3) && startInput.substring(0, 3) < list[i].endTime.substring(0, 3)
|| startInput.substring(0, 3) > list[i].startTime.substring(0, 3) && endInput.substring(0, 3) < list[i].endTime.substring(0, 3)
|| startInput.substring(0, 3) < list[i].startTime.substring(0, 3) && endInput.substring(0, 3) < list[i].endTime.substring(0, 3) && endTime.substring(0, 3) > list[i].startTime.substring(0, 3)
|| startInput.substring(0, 3) > list[i].endTime.substring(0, 3) && endInput.substring(0, 3) <= list[i].endTime.substring(0, 3)
|| startInput.substring(0, 3) > list[i].startTime.substring(0, 3) && endInput.substring(0, 3) == list[i].endTime.substring(0, 3)) {
alert('New appointments cannot start before previous one finishes');
return false
}
else
return true
}
else
return true
}
return true
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Tallying function:
var i;
//var yearArr = new Array(years[i]);
function summary() {
document.writeln('<table border="1">')
document.writeln('<tr><th>Year</th><th>Count</th></tr>')
for (i = 0; i < years.length; i++) {
document.writeln('<tr><td>' + years[i] + '</td>'
+ '<td>' + searchCount(years[i], years) + '</td></tr>')
}
document.writeln('</table>')
function searchCount(targetValue, arr) {
var count = 0; // Count of target value
var i = 0; // Iterative counter
// Examine each element.
for (i = 0; i < arr.length; i++) {
if (arr[i] == targetValue)
count++;
}
return count;
}
}
</script>
</head>
<body>
<title>Diary</title>
<h1 style="text-align: center;">Diary</h1>
<form>
<table bgcolor="#cccccc" cellpadding="5" cellspacing="0" align="center">
<tr>
<td align="right">Date</td>
<td><input type="text" id="date" name="date" size="10"></td>
<td align="right">Start Time</td>
<td>
<select id="startTime">
<option value="08:00">08:00</option>
<option value="09:00">09:00</option>
<option value="10:00">10:00</option>
<option value="11:00">11:00</option>
<option value="12:00">12:00</option>
<option value="13:00">13:00</option>
<option value="14:00">14:00</option>
<option value="15:00">15:00</option>
<option value="16:00">16:00</option>
<option value="17:00">17:00</option>
<option value="18:00">18:00</option>
</select>
</td>
<td align="right">End Time</td>
<td>
<select id="endTime">
<option value="08:00">08:00</option>
<option value="09:00">09:00</option>
<option value="10:00">10:00</option>
<option value="11:00">11:00</option>
<option value="12:00">12:00</option>
<option value="13:00">13:00</option>
<option value="14:00">14:00</option>
<option value="15:00">15:00</option>
<option value="16:00">16:00</option>
<option value="17:00">17:00</option>
<option value="18:00">18:00</option>
</select>
</td>
</tr>
<tr>
<td align="right">Subject:</td>
<td><input type="text" id="subject" size="10"></td>
</tr>
<tr>
<td align="right">Venue:</td>
<td><input type="text" id="venue" size="10"></td>
</tr>
<tr>
<td valign="top" align="center">Priority</td>
<td><input type="radio" id="high" name="Priority" value="High" checked="true" /> High<br />
<td><input type="radio" id="medium" name="Priority" value="Medium" /> Medium<br />
<td><input type="radio" id="low" name="Priority" value="Low" /> Low<br />
</td>
</tr>
</table>
<tr>
<div style="text-align:center;">
<td></td>
<td></td><input type="button" value="Add Appointment" onclick="addAppointment()" /></td>
</div>
</tr>
<hr>
<div>
<table align="center" width="80%" height="150px" cellpadding="1px" cellspacing="1px" border="1" id="table1">
<thead>
<tr>
<th width="50">Date</th>
<th width="20">Start</th>
<th width="20">End</th>
<th width="75">Subject</th>
<th width="60">Venue</th>
<th width="5">Priority</th>
</tr>
</thead>
<tbody id="tbody"> </tbody>
</table>
</div>
<tr>
<td></td>
<div style="text-align:center;">
<td></td><input type="reset" value="Randomise Appointments" onclick="shuffleAppointments()" /></td>
<td></td><input type="button" value="Sort Appointments" onclick="sortRecords()" /></td>
<td>by</td>
<td>
<select id="Date">
<option value="date">Date</option>
<option value="startTime">Start Time</option>
<option value="endTime">End Time</option>
<option value="subject">Subject</option>
<option value="venue">Venue</option>
<option value="priority">Priority</option>
</select>
</div>
</td>
</tr>
<hr>
<div style="text-align:left;">
<td></td><input type="button" value="Summary" onclick="summary()" /></td>
<td>by</td>
<td>
<select id="tallyOption">
<option value="year">Year</option>
<option value="date">Date</option>
<option value="optPriority">Priority</option>
</select>
</div>
</hr>
</form>
</body>
The problem is that you are calling validDate() to make the comparison each time and inside the validDate function you are mutating the years variable.
There are multiple ways to fix it but in my opinion the first one and the most basic, which I strongly suggest, is to store the value of validDate() in a constant and make the further comparisons with it. You should always try to avoid calling the function each time. It's better to save its result in memory
Where you have
if (validDate() != false) { newAppointment.date = validDate(); }
inside the addApointment function, just go for
const isDateValid = validDate()
and then replace all the upcoming ocurences (5) of validDate() with isDataValid
const isDateValid = validDate()
if (isDateValid != false) { newAppointment.date = isDateValid; }
and
if (isDateValid === null | isDateValid === undefined | validTime() === null | validTime() === undefined | validTime() === false | isDateValid === false | isConcurrentAppointment(newAppointment.date, newAppointment.startTime, newAppointment.endTime) != true) {
alert('Date or time entry invalid')
}
And of course I strongly suggest you to do the same for validTime.
Your problem seems to come from appending to years within the validDate function, which is treated as a non-mutating function elsewhere in the code. Since validDate is repeatedly called within the addAppointment function every time tha value is needed, the years.push(yy) line will also be called repeatedly. You could move the years.push(yy) line elsewhere, but the better solution would be to change addAppointment so that it calls validDate and validTime once each, stores their values, and then performs the rest of the operations on the stored values. However, you might also want to move the years.push(yy) so that it is only called when an appointment is completely valid.

Prevent a column from being compared

I have a table with three columns: a, b and c. The above code works for column a, b and c. The third column gives undefined value. I want to prevent this column from comparing, i.e. if I enter values in column a and b and leave column c as it is, the data should be saved. How to achieve this?
function saving(id) {
var store;
$('#mt .tb tr td').each(function() {
var value = $(this).find("input").val();
if (value === '' || value == null || value == " ")
store == "0";
else
store == "1";
});
if (store = "0") {
alert("empty rows cannot be saved")
return false;
} else
return true;
alert("saving successful")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mt">
<tr>
<thead>
<th>a</th>
<th>b</th>
<th>c</th>
</thead>
</tr>
<tr>
<tbody class="tb">
<td><input id="a"></td>
<td><input id="b"></td>
<td><i class="fa fa-pencil Addbtn"></i></td>
</tbody>
</tr>
<input type="submit" value="Save" onclick="return saving()">
</table>
You can add a class to the columns you don't want to compare
<td class='nocompare'>
and exclude those
$('#mt .tb tr td:not(.nocompare)').each
(or you could add compare to the ones you do want to compare to remove the double negative.
There were some other fundamental issues with the code:
setting a value uses = not == (store == 0)
comparing a value uses == (or ===) not = (if (store = 0))
you had an alert after the last return which would never get hit
by setting store = 1, your check only needs the last column to have a value and will pass if all of the ones before failed.
for the last issue, you can add up a count of all the passes and compare with how many there should be, eg:
var pass = 0;
$('#mt .tb tr td.check').each(function() {
var value = $(this).find("input").val();
if (value === '' || value == null || value == " ")
; // fail
else
pass++;
});
if (pass == $('#mt .tb tr td.check').length))
// all passed
or you can go with a bit flag and AND it as below.
function saving(id) {
var store = 1;
$('#mt .tb tr td.check').each(function() {
var value = $(this).find("input").val();
if (value === '' || value == null || value == " ")
store = 0;
else
store = store & 1;
});
if (store == "0") {
alert("empty rows cannot be saved")
return false;
} else {
alert("saving successful")
return true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mt">
<tr>
<thead>
<th>a</th>
<th>b</th>
<th>c</th>
</thead>
</tr>
<tr>
<tbody class="tb">
<td class='check'><input id="a"></td>
<td class='check'><input id="b"></td>
<td><i class="fa fa-pencil Addbtn"></i></td>
</tbody>
</tr>
<input type="submit" value="Save" onclick="return saving()">
</table>

Get value from elements from table

I have the next table:
<table id="table_id">
<tr>
<td>Test</td>
<td>Description</td>
<td>Date</td>
</tr>
<tr>
<td><select>
<option val="1">Math</option>
<option val="2">Chemistry</option>
<option val="3">Biology</option>
</select></td>
<td><input type="text" id="txt_desc"/></td>
<td><input type="text" id="date"/></td>
</tr>
</table>
And the next javascript code for get the values
val_test_op = '';
parent.$('#table_id option:selected').each(function (index,value){
test = $.text(value).trim();
if ( index === 0 && test || index % 1 === 0 && test ) {
val_test_op += index +' TEST: ' + test;
return;
}
})
val_test_input = '';
parent.$('#table_id td>input').each(function (index,value){
test = this.value;
if ( index === 0 && test || index % 2 === 0 && test ) {
texto_examen_input += index +' Description: ' + test;
return;
}
if ( index === 1 && test || index % 3 === 0 && test ) {
texto_examen_input += index +' Date: ' + test;
return;
}
})
My question is: ¿ How i get the value from the option:selected and input text in a only "each function" ?
I don't think you need a each function for getting values from fields in the table.
If you add ids to the fields, you could select those directly with jquery then use the val function to get their values easily.
<table id="table_id">
<tr>
<td>Test</td>
<td>Description</td>
<td>Date</td>
</tr>
<tr>
<td><select id="txt_test">
<option val="1">Math</option>
<option val="2">Chemistry</option>
<option val="3">Biology</option>
</select></td>
<td><input type="text" id="txt_desc"/></td>
<td><input type="text" id="txt_date"/></td>
</tr>
</table>
Then with javascript:
val_test_op = $('#txt_test').val();
texto_examen_desc = $('#txt_desc').val();
texto_examen_date = $('#txt_date').val();
If you really want to use a single each function to get all the values, you could use the :input selector that jquery provides and do the following:
values = '';
$('#table_id').find(':input').each(function (index, input) {
values += $(input).val();
});
I added in a button to alert what the selected value is.
function myFunction(){
var theSelect = document.getElementById("table_id").getElementsByTagName("select")[0];
var selectedOption = theSelect.options[theSelect.selectedIndex].text;
alert(selectedOption);
}
document.getElementById("myButton").addEventListener("click", myFunction, false);
https://jsfiddle.net/e1hxn6kL/
Give your select an ID such as id="opts"
Then
var opts = [];
$.each($("#opts:selected"),function(opt){
opts.push(opt.Val());
}
var txt_desc = $("#txt_desc").Val();
var date = $("#date").Val();
Or similar

Jquery to sort drop down list in a table row

How can I sort the drop down list below? I need to sort it by name as well as remove certain options say the ones beginning with 'S'.
<table>
<tr>
<td class="bold">Program Link</td>
<td>
<select name="ProgramLink">
<option value="0">None Selected</option>
<option value="2985">Cluster</option>
<option value="2986">Seminar</option>
<option value="2991">Services</option>
<option value="2982">Biliteracy</option>
<option value="2983">Learner MEC</option>
<option value="2987">Day Class</option>
</select>
</td>
</tr>
</table>
I think this code plus adding order class to your select may help:
$('select.order').each(function() {
var options = [];
$(this).find('option').each(function() {
if ($(this).text().indexOf('S') != 0) {
options.push({value: $(this).val(), label: $(this).text()});
};
})
if (options.length > 0) {
options = options.sort(function(a, b) {
var x = a['label']; var y = b['label'];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
var options_html = '';
$.each(options, function(i, option) {
options_html += '<option value="'+option.value+'">'+option.label+'</option>';
});
$(this).html(options_html);
};
})
Note: your html code lacks the </select> ;)
var options = $('select option');
options.detach().sort(function(a,b) {
var at = $(a).text();
var bt = $(b).text();
return (at > bt)?1:((at < bt)?-1:0);
});
options.appendTo('select');

jQuery/Javascript compare two tables against each other

I need to compare two HTML tables' rows assuming that data in first cell can be duplicated but data in second cell is always unique. I need to find whether first cell AND second cell in table1 is the same as data in first cell AND second cell in table2 for instance:
Table1:
<Table>
<tr>
<td>123</td>
<td>321</td>
</tr>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>0</td>
<td>312</td>
</tr>
<tr>
<td>123</td>
<td>323331</td>
</tr>
</Table>
Second table:
<table>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>545</td>
<td>3122</td>
</tr>
<tr>
<td>123</td>
<td>321</td>
</tr>
</table>
The result of this should be:
123 321 - good, do nothing
545 345 - good, do nothing
545 3122 - wrong its not in table1 <-
Here's what I've got so far...
$('#runCheck').click(function(){
var firstTable = $('#firstDiv table tr');
var secondTable = $('#secDiv table tr');
$(secondTable).each(function(index){
var $row = $(this);
var secTableCellZero = $row.find('td')[0].innerHTML;
var secTableCellOne = $row.find('td')[1].innerHTML;
$(firstTable).each(function(indexT){
if ($(this).find('td')[0].innerHTML === secTableCellZero){
if ($(this).find('td')[1].innerHTML !== secTableCellOne){
$('#thirdDiv').append("first: " + secTableCellZero + " second: " + secTableCellOne+"<br>");
}
}
});
});
});
Where am I going it wrong?
Just to clarify once again:
2nd table says :
row1 - john|likesCookies
row2 - peter|likesOranges
1st table says :
row1 - john|likesNothing
row2 - john|likesCookies
row3 - steward|likesToTalk
row4 - peter|likesApples
now it should say :
john - value okay
peter - value fail.
a lot alike =VLOOKUP in excel
Check this working fiddle : here
I've created two arrays which store values in each row of tables 1 and 2 as strings. Then I just compare these two arrays and see if each value in array1 has a match in array 2 using a flag variable.
Snippet :
$(document).ready(function() {
var table_one = [];
var table_two = [];
$("#one tr").each(function() {
var temp_string = "";
count = 1;
$(this).find("td").each(function() {
if (count == 2) {
temp_string += "/";
}
temp_string = temp_string + $(this).text();
count++;
});
table_one.push(temp_string);
});
$("#two tr").each(function() {
var temp_string = "";
count = 1;
$(this).find("td").each(function() {
if (count == 2) {
temp_string += "/";
temp_string = temp_string + $(this).text();
} else {
temp_string = temp_string + $(this).text();
}
count++;
});
table_two.push(temp_string);
});
var message = "";
for (i = 0; i < table_two.length; i++) {
var flag = 0;
var temp = 0;
table_two_entry = table_two[i].split("/");
table_two_cell_one = table_two_entry[0];
table_two_cell_two = table_two_entry[1];
for (j = 0; j < table_one.length; j++) {
table_one_entry = table_one[j].split("/");
table_one_cell_one = table_one_entry[0];
table_one_cell_two = table_one_entry[1];
console.log("1)" + table_one_cell_one + ":" + table_one_cell_two);
if (table_two_cell_one == table_one_cell_one) {
flag++;
if (table_one_cell_two == table_two_cell_two) {
flag++;
break;
} else {
temp = table_one_cell_two;
}
} else {}
}
if (flag == 2) {
message += table_two_cell_one + " " + table_two_cell_two + " found in first table<br>";
} else if (flag == 1) {
message += table_two_cell_one + " bad - first table has " + temp + "<br>";
} else if (flag == 0) {
message += table_two_cell_one + " not found in first table<br>";
}
}
$('#message').html(message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="one">
<tr>
<td>123</td>
<td>321</td>
</tr>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>0</td>
<td>312</td>
</tr>
<tr>
<td>123</td>
<td>323331</td>
</tr>
</table>
<hr>
<table id="two">
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>545</td>
<td>3122</td>
</tr>
<tr>
<td>123</td>
<td>321</td>
</tr>
</table>
<hr>
<div id="message">
</div>
</div>
If I understand your requirements, it would be easier to read the first table and store the couples as strings: 123/321, 545/345, etc...
Than you can read the second table and remove from the first list all the rows found in both.
What remains in the list are couples that do not match.
From purely an efficiency standpoint if you loop through the first table just once and create an object using the first cell value as keys and an array of values for second cells, you won't have to loop through that table numerous times
this then makes the lookup simpler also
var firstTable = $('#firstDiv table tr');
var secondTable = $('#secDiv table tr');
var firstTableData = {}
firstTable.each(function() {
var $tds = $(this).find('td'),
firstCellData = $tds.eq(0).html().trim(),
secondCellData == $tds.eq(1).html().trim();
if (!firstTableData[firstCellData]) {
firstTableData[firstCellData] = []
}
firstTableData[firstCellData].push(secondCellData)
})
$(secondTable).each(function(index) {
var $tds = $(this).find('td');
var secTableCellZero = $tds.eq(0).html().trim();
var secTableCellOne = $tds.eq(1).html().trim();
if (!firstTableData.hasOwnProperty(secTableCellZero)) {
console.log('No match for first cell')
} else if (!firstTableData[secTableCellZero].indexOf(secTableCellOne) == -1) {
console.log('No match for second cell')
}
});
I'm not sure what objective is when matches aren't found

Categories

Resources