compare values of cells in different rows in table using jquery - php

I have a dynamically generated table with php that has same rows. Need to get value from cell 1 in row 1 and value from cell 1 in row 2 and compare them. If they are the same remove entire row or hide... Do that for the whole table... Any help is appreciated.. Thanks!!
Haave this so far:
var numRows = $('table#changeSubjectKatedra tr').lenght;
var i = 0;
do {
var cur = $('input#'+i).val();
var next = $('input#'+(i+1)).val();
if(cur == next){
$('tr#'+i).remove();
}
i++;
} while(i<numRows);
The row in table looks like this:
<tr id='idNum'><td>someText<input type='hidden' value='someData' id='idNum'>
</td><td>someText</td></tr>

Note 1. You should do in on server side with PHP, not with JavaScript.
Note 2. You must use unique id for each element.
Note 3. Avoid using numerical ids of elements.
Note 4. You don't need ids at all for doing what you want.
If you still want to do it in JavaScript, I suggest you to do it this way: (live demo here)
var rows = $("#changeSubjectKatedra tr");
for(var i = 0; i <= rows.length - 2; i++) {
if ($(rows[i]).find("input").val() ==
$(rows[i+1]).find("input").val()) {
$(rows[i]).remove();
}
}

You can use jQuery's .each function. This should work according to the description you provided:
$('table#changeSubjectKatedra tr').each(function() {
if (repeat == $(this).children("input")[0].value) {
$(this).remove();
}
repeat = $(this).children("input")[0].value;
});

Related

Add colgroup for each table column

There are probably other similar posts, but here goes nothing.
I am currently reworking on an existing site and some of the changes required involves column and row highlighting, like here (tutorial / demo).
Since there are several web pages to go through, I would like to have some kind of shortcut to dynamically add <colgroup></colgroup> like in the example without having to go through each page and table by hand.
I've considered php's preg_replace function, but I doubt that's the simplest way to go around it. In an optimal scenario, I would be able to verify if there is an existing <colgroup></colgroup> array for each column.
Using jQuery you could dynamically prepend the <colgroup></colgroup> to each table before your highlight script. Something like -
if($("table > colgroup").length == 0){ // If the table does not have <colgroup></colgroup>
var colCount = 0;
$('tr:nth-child(1) td').each(function () { // Get the count of table columns
if ($(this).attr('colspan')) { // if there is a <td colspan>
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
});
var colgroupList = '';
for (i=0;i<colCount;i++){ // Add a <colgroup></colgroup> for each <td>
colgroupList += '<colgroup></colgroup>';
}
$("table").prepend(colgroupList);
}
$("table").delegate('td','mouseover mouseleave', function(e) {
...
jsFiddle example http://jsfiddle.net/BGR22/1/
Edit
If you have multiple tables on a page, you need to add a selector to only get the parent table -
var $table = $(this).closest("table");
So now your $("table").delegate() would look like
$("table").delegate('td','mouseover mouseleave', function(e) {
var $table = $(this).closest("table");
if (e.type == 'mouseover') {
$(this).parent().addClass("hover");
$table.children("colgroup").eq($(this).index()).addClass("hover");
} else {
$(this).parent().removeClass("hover");
$table.children("colgroup").eq($(this).index()).removeClass("hover");
}
});
Updated jsFiddle - http://jsfiddle.net/BGR22/3/
and with 3 tables - http://jsfiddle.net/BGR22/4/

How to find the cell index when rowspans are involved

I am working on a scheduling project and have run into an issue with finding the column index of a selected cell (so that i may then get the appropriate header for the column). The issue comes into play when a previous cell(or cells) have/has a rowspan. In which case the cell index is off by that amount of cells. I have been at this since yesterday. My current attempt involves using a solution I found in previous posts, and this is this:
parentTr.find('>td, >th').each(function(i,o) {
if ( this == reference )
{
cellNum = i;
var counter = columnNum;
while ( counter-- )
{
$(this).closest('tr').next().find('>td,>th').each(function(i,o)
{
if ( cellNum == i )
{
$(this).addClass('rowspan-affected');
$(this).attr('colNum', columnNum);
}
});
}
}
});
})
The problem is that this solution counts the number of rowspanned cells on the entire page. I need a count of the rowspanned cells for only the current clicked cell, and then be able to add that count to index so I can get the proper header. What I have been trying looks like this:
var $this = $(this);
//get the row header contents
var row = $this.parent('tr').contents('th:eq(0)').html();
//trying this
var colCount = $(this).prevAll().find('td').parent('tr').attr('rowspan');
alert (colCount);
//used to get the cell index
var rowIndex = $(this).parent().index('.main tbody tr');
var tdIndex = $(this).index('.main tbody tr:eq('+rowIndex+') td');
//alert ("tdindex " + (tdIndex+1));
var headerObj = $(this).parents('.main').find('th').eq(tdIndex+1);
//strip whitespace before passing
var toPass = $.trim(headerObj.text());
//toPass = $.trim(toPass)
//alert (toPass);
This information is gathered and then passed to a new form with the selected information used to populate the form.
If anyone can help me with this, I would be greatly appreciative!!!

How to print rows with JavaScript

I am currently using
rows.length
in JS and it's giving me the number of rows as output.
The actual code is like this
oResources.html("<h3>Number of Rows = "+ rows.length+"</h3>");
The output is Number of Rows = 1
But I want to see the values of the rows not the number of rows.
The whole function looks like below after editing:
this.get_resources = function(rows)
{ var oResources = $('#resources-'+ options.plugin_uuid);
//oResources.html("<h3>Number of Rows = "+ rows.length+"</h3>");
//oResources.html("<h3>Content of Rows = "+ rows.join(' :: ')+"</h3>");
var data = ""; // Temporary `data` variable
for(var key in rows) { // Loop through the rows
if(rows.hasOwnProperty(key)){
data += rows[key] + "<br />\n"; // Add the current row to the data
}
}
oResources.html(data); // Display the data
//console.log(rows.length);
};
Now it's printing out [object] [object]
My question is:
The output is supposed to be an email id instead of [object] [object]. How to solve this?
Something like that?
oResources.html("<h3>Content of Rows = "+ rows.join(' :: ')+"</h3>");
EDIT: As your data format seems to have another level of depth, I've made a fiddle to give some insight on what you could do. http://jsfiddle.net/TyeQE/
try this:
var data = ""; // Temporary `data` variable
for(var key in rows) { // Loop through the rows
if(rows.hasOwnProperty(key)){
data += rows[key] + "<br />\n"; // Add the current row to the data
}
}
oResources.html(data); // Display the data
Yes, 'rows' looks like an array. You need a for loop to go over the array and print it out.
var str = ""
for(var i = 0; i < rows.length; i++) {
str = rows[i] + "<br>";
}
oResources.html($str);
Try console.log(rows). Open console (usualy F12) in the browser to see the result.

array of same id using getElementById error

i want to create array of same id or name using getElementById..
i have a "add button", when the user press this button, its generate a dropdown list(dynamic) which the value is get from mysql..
and its looks like this when the user press 3 times..
i want to create an array of this id, and store it to mysql..
this is my JS code :
var menu_paket_array = document.getElementById('menu_paket').value;
alert(menu_paket_array);
the problem is, when i try to create this array(menu_paket_array), the value in this array is just the first id (Test 1) only..
how can i fix this?
thanks...
Using the same id for more than one element is wrong. Id is to uniquely identify certain element. Using it for more elements defeats its -purpose. If you need that for i.e. CSS styling, then use class instead, which is designed just for such scenarios.
An ID must be unique on a page. You can only use it on one element.
Instead, use a CSS class or element type to iterate (here's a fiddle demonstrating this code):
function alertValues() {
var select, selects = document.getElementsByTagName('select');
var out = "";
for (var i = 0; i < selects.length; i++) {
select = selects[i];
if (select.className && select.className.match(/CLASSNAME_TO_INCLUDE/)) {
out += select.options[select.selectedIndex].value;
}
}
alert(out);
}
A better solution, of course, would be to utilize a dom library like jQuery or mootools, with which you could do something like this:
jQuery(function($) {
vals = [];
$('select.CLASSNAME').each(function() { vals.push($(this).val()); });
alert(vals.join(','));
});
document.getElementsByClassName(names);
Where names is the classname u generate for each one.
Instead of assigning each element with id='menu_paket' (for the reasons #WebnetMobile.com explained) assign class='menu_paket'.
Instead of var menu_paket_array=document.getElementById('menu_paket').value;, do
var temp_array = document.getElementsByClassName('menu_paket');
var menu_paket_array = [];
for(i in temp_array){
menu_paket_array[] = temp_array[i].value;
}

is there a better way to code a quotation form?

i am seeking advise and probably example code, links that will help me improve my quotation form. the current scenario is like that:-
dynamic (select combo) rows are generated for items(from mysql database) along with empty input boxes for price and quantity. the user adds or deletes the rows based on no. if items required and fills up the price, quantity etc and then is taken to a second form with all calculated values, etc so he can print the same or send it through email.
now the items count is approx 3500 so when the user reaches 5th or 6th row, it starts becoming extremely slow to add a new row. i need to pull mysql items from database since they keep increasing every now and then.
any help is much appreciated. thanks in advance.
following is the javascript code for dynamic lines that i am currently using:-
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
following is the php code that i am using to pull mysql items to the select combo box
<?php
$con = mysql_connect('connection details');
if (!$con) {
die('Could not connect: ' . mysql_error());}
$db=mysql_select_db('database',$con);
$extract1=mysql_query("query")
OR die(mysql_error());
$numrows1=mysql_num_rows($extract1);
echo "<select name='item[]' title='selectItemName'>";
echo "
<option>Select Item Description</option>
";
while ($row1=mysql_fetch_assoc($extract1))
{
$ic[]=$row1['ItemName'];
}
foreach ($ic as $i){
echo "<option>".$i."</option>";
}
echo "</select>";
mysql_close($con);
?>
i also tried the following example from jquery which is pretty neat. but i am new and do'nt know how to populate the rest of the boxes along with the select box. here's the code
<script type="text/javascript">
$(document).ready(function() {
$("select[multiple]").asmSelect({
addItemTarget: 'bottom',
animate: true,
highlight: true,
sortable: true
});
});
</script>
I don't see where addRow and deleteRow are being called, but I will say here is where some of your inefficiencies may come:
1. var table = document.getElementById(tableID);
2. var rowCount = table.rows.length;
3. var row = table.insertRow(rowCount);
4. var colCount = table.rows[0].cells.length;
Every time you add a row, you're searching the document for the table, which is expensive if you're only working on one table; consider a global variable and doing something like var table = glob_table || document.getElementById(..);
Even though it's a property and isn't as expensive to fetch, this could still be tedious when you could increment/decrement another global variable.
I'm not sure it's proper to add a row to a table, before you add the cells to the row. I'd have to look into this update: I guess it is
(same as #2)
BTW, you're using jQuery at the bottom. Personally, I don't like using jQuery, but if you're going to load it, you've already done most of the damage in slowing down your page, so you might as well use it. It's actually pretty good at adding/removing elements, so I would advise you read some jQuery tutorials.
Also, if your database is increasing, then instead of re-creating the options, you'll only want to update it with items that aren't already loaded. Therefore, you need to use a timpestamp on your database records and store that timestamp in your JavaScript/page in order to "refresh since" (where update_ts >= $last_update_param)
A select combo with ~3500 items? Ouch. (times N for number of rows? Double Ouch.)
Think it may be time to rethink the implementation. I'd probably do a popup window or something for selecting the item that [when closed] populates the form field. Keep the form only holding the value, not value+3500 (times row count).
(Best example I can give is phpBB and when you're in the Admin Control Panel selecting a user you want to manage. They pop-out with the entire [filterable] database then bring the value back to the parent window. I can see this also being advantageous for the user to find an item within 3500 entries, and not scrolling through a select combo)

Categories