Search box for table - javascript

Given this table:
<table class="tbllist searchtbl" cellpadding=2 cellspacing=0 style="width: 70%">
<tr>
<th class="hidden">ID</th>
<th>Number Plate</th>
<th>Chassis Number</th>
<th>Trailer Make</th>
<th>Year</th>
<th>Axles</th>
<th></th>
</tr>
<tr class='tbl'>
<td class='hidden'>3</td>
<td>
<input type=text style = 'width: 75px' class='centered' id='trnumberplate_3' name='trnumberplate_3' value='T212ABS' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trnumberplate", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 200px' id='trchassisnumber_3' name='trchassisnumber_3' value='AJSDGASJH' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trchassisnumber", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 200px' id='trmake_3' name='trmake_3' value='LOW LOADER' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trmake", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 50px' class='centered' id='tryear_3' name='tryear_3' value='2009' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","tryear", this.value ,"trid","3","1","",this, "false")'>
</td>
<td>
<input type=text style = 'width: 25px' class='centered' id='traxles_3' name='traxles_3' value='3' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","traxles", this.value ,"trid","3","1","",this, "false")'>
</td>
<td class='delbtn'>
<button id='trailers_3' title='DELETE THIS ITEM (3)?' onclick='event.preventDefault(); delitem("trailers","trid","3","trailers.php","#workspace")'><img src='/icons/delete.png' ></button>
</td>
</tr>
</table>
I have the following search function:
function searchbox() {
// text input search for tables (such as trip history etc)
$("#search").keyup(function () {
//split the current value of searchInput
var data = this.value.toUpperCase().split(" ");
//create a jquery object of the rows
var jo = $(".tbllist").find("tr").not("tr:first"); // exclude headers
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
})
It will loop through table td's to check if the searched value is available and filter rows. It is not filtering if the td contains an input text element with the searched value.
Update:
if ($t.find("input").val().toUpperCase().indexOf(data[d]) > 0) {
return true;
}
Now works but will only matches the first column of the table.
JSFiddle: https://jsfiddle.net/fabriziomazzoni79/30d52c9z/

Change jo.filter() like this:
jo.filter(function (i, v) {
var txt = '';
$(v).find("input").each(function(n,e){
txt += e.value;
});
for(var d=0; d<data.length; d++){
if (txt.search(data[d])>=0) {
return true;
}
}
return false;
})
Fiddle here.

Related

Incrementing id attribute value through javascript

I am trying to dynamically add rows to a table to take orders and have created a javascript function for it.
function addnewrow()
{
var lastid = $("#table tr:last").attr("id");
var newid=lastid+1;
var newcolumn = document.createElement("tr");
newcolumn.id=newid;
newcolumn.innerHTML = "<td id='no"+newid+"'><a class='cut'>-</a>"+newid+"</td>"+
"<td>"+
"<ajaxToolkit:ComboBox ID='prod"+newid+"' runat='server' DataSourceID='SqlDataSource2' DataTextField='pname' DataValueField='pid' MaxLength='0' style='display: inline;'></ajaxToolkit:ComboBox>" +
"</td>"+
"<td><input type='number' required='required' min='1' name='quantity" + newid + "' /></td>" +
"<td id='price" + newid + "'></td>" +
"<td id='amount" + newid + "'></td>";
document.getElementById("table").appendChild(newcolumn);
}
I am doing this to get the values of all the elements in the code behind file to put them in database.
but due to this i get an error in the aspx.designer.cs page saying semicolon expected
protected global::AjaxControlToolkit.ComboBox prod" + newid + ";
ASP.NET Code
<table class="Grid" id="table">
<tr>
<td colspan="5">Enter Order Details</td>
</tr>
<tr>
<th>Sr No.</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
<tr id="1">
<td><a class="cut">-</a>1</td>
<td>
<ajaxToolkit:ComboBox ID="prod1" runat="server" DataSourceID="SqlDataSource2" DataTextField="pname" DataValueField="pid" MaxLength="0" style="display: inline;"></ajaxToolkit:ComboBox>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:micoConnectionString %>" SelectCommand="SELECT [pid], [pname] FROM [Products]"></asp:SqlDataSource>
</td>
<td><input type="number" required="required" min="1" name="quantity1" /></td>
<td id="price1"></td>
<td id="amount1"></td>
</tr>
</table>
<a class="add" onclick="addnewrow()" href="#">+</a>
Check this
$("#btnAddSchedule").click(function () {
var trs = $("[id^=trSchedules]");
var numberofrows = trs.length;
var newtr = $('#' + trs[0].id).clone();
$(newtr).attr('id', $(newtr).attr('id').replace(/\d+/, numberofrows));
newtr.find("input,select,img").each(function () {
$(this).attr('id', $(this).attr('id').replace(/\d+/, numberofrows));
$(this).attr('name', $(this).attr('name').replace(/\d+/, numberofrows));
if ($(this).attr('type') != "hidden") {
$(this).val('');
}
else if ($(this).attr('id').indexOf('DataExportQueueID') == -1) {
$(this).val('');
}
if ($(this).attr("type") == "checkbox") {
$(this).removeAttr("checked");
$(this).parent().html($(this).parent().html().replace(/\d+/g, numberofrows));
}
if ($(this).attr("type") == "button") {
$(this).attr("onclick", "deleteSchedule(this,0);");
}
});
$('#' + trs[numberofrows - 1].id).after(newtr);
CrossCheckScheduleRows();
});
function CrossCheckScheduleRows() {
$('[id^=trSchedules]').each(function () {
var row = $(this);
var index = row[0].rowIndex - 2;
row.attr('id', row.attr('id').replace(/\d+/, index));
row.find("input,select,img").each(function () {
$(this).attr('id', $(this).attr('id').replace(/\d+/, index)).attr('name', $(this).attr('name').replace(/\d+/, index));
});
});
}
I use this for the same purpose, maybe it will help you

Unable to remove the selected input rows from a table

I have multiple input tags in a table of type "checkbox". I need to remove the complete row of selected checkbox.
I am using the following function to remove the selected rows:
function removeSelected( tblname )
{
var tbl = document.getElementById(tblname);
var rowcount = tbl.rows.length;
if (tbl.rows.length > 1)
{
for ( var i = 0 ; i < tbl.rows.length ; i++)
{
var row = tbl.rows[i];
var chkselect = row.cells[0].getElementByTagName("input").item(0);
var attr = trimString(row.cells[0].getElementByTagName("input").item(1).value);
var attr1 = trimString(row.cells[0].getElementByTagName("input").item(2).value);
if (chkselect.checked)
{
tbl.deleteRow(i);
i = 0;
}
}
}
}
And My html is as below:
<table id="myTable" border = "0">
<tr border = "0">
<td><input type="checkbox" name="checkbox" id = "checkbox" value = "hen">hen</input></td>
</tr>
<tr>
<td><input type = "checkbox" name="checkbox1" id="checkbox1" value = "cock">cock</input></td>
</tr>
</table>
<br>
<button onclick="removeSelected("myTable")">Try it</button>
When I check the "hen" checkbox it should delete the hen row and when I check "cock" it should delete the cock row. However, I am unable to delete the selected one.
What am I doing wrong?
As AleJuliet said, you should fix syntax errors.
And to delete rows, you should start from the end, because the rows are shifted
function removeSelected( tblname ) {
var tbl = document.getElementById(tblname);
for ( var i = tbl.rows.length - 1 ; i >= 0 ; i--) {
checkbox = tbl.rows[i].getElementsByTagName("input")[0];
if(checkbox.checked){
tbl.deleteRow(i);
}
}
}
<table id="myTable" border = "0">
<tr border = "0">
<td><input type="checkbox" name="checkbox" id = "checkbox" value = "hen">hen</input></td>
</tr>
<tr>
<td><input type = "checkbox" name="checkbox1" id="checkbox1" value = "cock">cock</input></td>
</tr>
</table>
<br>
<button onclick="removeSelected('myTable')">Try it</button>

Can't get numbers to swap in my JQuery function when I swap table rows

I have created a jquery function that allows me to click on the UP arrow and it swaps rows in a table. I have rank numbers in each row. But I can only get the clicked number to change. I want both numbers to swap. I know it is something with getting the value in abovecnt. I just can't figure out how to get that value of the row above. Right now it is just undefined.
http://jsfiddle.net/Thread7/2rmowem4/15/
$('.change-rank').click(function() {
var cnt = $(this).attr('cnt');
var direction = $(this).attr('data-direction'),
$original = $(this).closest("tr"),
$target = direction === "up" ? $original.prev() : $original.next();
if ( $target.length && direction === "up" ) {
$original.insertBefore($target);
abovecnt = $original.find('.ranky input[type="text"]').val();
$('#rank_' + cnt).val(cnt-1);
$('#rank_' + abovecnt).val(cnt);
alert('abovecnt=' + abovecnt + '|cnt=' + cnt);
}
else if( $target.length ) {
$original.insertAfter($target);
}
});
Note: I'll eventually want the down arrow to swap also, but right now just trying to get it to work.
I converted your cnt attributes to data attributes for this.
EDIT: updated JS snippet to #tripleb 's recommendation: before and after .. as opposed to doing inserts and changing values of the arrows.
Sample Code Snippet
$('.change-rank.up').click(function(ev) {
var $original = $(this).closest("tr"),
$target = $original.prev();
if ($target.length) {
var cnt = $original.data('cnt'),
targetcnt = $target.data("cnt");
if (targetcnt) {
$original.after($target);
alert(targetcnt);
}
}
});
$('.change-rank.down').click(function(ev) {
var $original = $(this).closest("tr"),
$target = $original.next();
if ($target.length) {
var cnt = $original.data('cnt'),
targetcnt = $target.data("cnt");
if (targetcnt) {
$original.before($target);
alert(targetcnt);
}
}
});
.change-rank.up:after {
content: attr(data-icon);
}
.change-rank.down:after {
content: attr(data-icon);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Rank</td>
<td>Username</td>
</tr>
<tr data-cnt='1'>
<td>
1</td>
<td>Joey</td>
<td>
<input type='text' id='rank_1' class='ranky' value='1' />
</td>
</tr>
<tr data-cnt='2'>
<td>
2</td>
<td>Randy</td>
<td>
<input type='text' id='rank_2' class='ranky' value='2'>
</td>
</tr>
<tr data-cnt='3'>
<td>
3</td>
<td>Bobby</td>
<td>
<input type='text' id='rank_3' class='ranky' value='3' />
</td>
</tr>
<tr data-cnt='4'>
<td>
4</td>
<td>Jesse</td>
<td>
<input type='text' id='rank_4' class='ranky' value='4' />
</td>
</tr>
</table>
JsFiddle: Example
why not this:
if ( $target.length && direction === "up" ) {
$original.after($target)
}
else if( $target.length ) {
$original.before($target);
}
http://jsfiddle.net/2rmowem4/16/

Not getting input inside td with jQuery?

I have a problem not getting the <input> inside a specified <td>. Through jQuery, I want once an "input search" entered, get just those <tr> that have these entries.Then when the input is empty return all the entries.
Here is my code :
<table id="hosts">
<tr>
<th>First</th>
<th>Second</th>
</tr>
<tr>
<td id="host"><input type="text" id="inputhost" value="214215" size="16"></td>
<td id="rand"><input type="text" id="inputrand" value="442" size="16"></td>
</tr>
<tr>
<td id="host"><input type="text" id="inputhost" value="1252512" size="16"></td>
<td id="rand"><input type="text" id="inputrand" value="556" size="16"></td>
</tr>
<tr>
<td id="host"><input type="text" id="inputhost" value="2114" size="16"></td>
<td id="rand"><input type="text" id="inputrand" value="4666" size="16"></td>
</tr>
<tr>
<td id="host"><input type="text" id="inputhost" value="3245466" size="16"></td>
<td id="rand"><input type="text" id="inputrand" value="22654" size="16"></td>
</tr>
<tr>
<td id="host"><input type="text" id="inputhost" value="24588" size="16"></td>
<td id="rand"><input type="text" id="inputrand" value="54877" size="16"></td>
</tr>
</table>
<br />
<input type="text" id="search" placeholder=" live search"></input>
and this is my jQuery code:
function removeHighlighting(highlightedElements) {
highlightedElements.each(function () {
var element = $(this);
element.replaceWith(element.html());
})
}
function addHighlighting(element, textToHighlight) {
var text = element.text();
var highlightedText = '<em>' + textToHighlight + '</em>';
var newText = text.replace(textToHighlight, highlightedText);
element.html(newText);
}
$("#search").on("keyup", function () {
var value = $(this).val();
removeHighlighting($("table tr em"));
$("#hosts tr").each(function (index) {
if (index !== 0) {
$row = $(this);
var $host = $row.find("#host input#inputhost");
var $dest = $row.find("#rand input#inputrand");
var host_id = $host.text();
var dest_id = $dest.text();
var hostIndex = host_id.indexOf(value);
var destIndex = dest_id.indexOf(value);
if ((hostIndex == -1) && (destIndex == -1)) {
$row.hide();
}
else if ((hostIndex != -1) && (destIndex != -1)) {
addHighlighting($host, value);
addHighlighting($dest, value);
$row.show();
}
else if (hostIndex != -1) {
addHighlighting($host, value);
$row.show();
}
else {
addHighlighting($dest, value);
$row.show();
}
}
});
});
Duplicate IDs! You don't really need them; remove them and then your code will be:
var $host = $row.find("td:first input");
var $dest = $row.find("td:eq(1) input");
UPDATE
You also have to update your code to:
var host_id = $host.val();
var dest_id = $dest.val();
DEMO
You cant give Id like that. Id should be unique. change them to class. then it will work. Then your selector will be
$(this).find(".host input.inputhost")

Cannot extract data from TD if there is span in front

I need your help.
Because of the way IE7 chooses to ignore the TD: whitespace: nowrap, I am forced to put and use spans in front of my TD's so here's the delema. When I click on a table row that has no spans in between the td's, the coding is able to extract the data and highlight the row.
However, when I introduce a span in between my td's and click to select a single cell in the table row with the spans's I get the following error: "cells.0 is null or not an object." I know that if I click a little bit off the side of the table cell it works, but I need to be able to also click on the <TD> and <SPAN> areas and have the code work.
Since I am making a table that will have all <span></span>'s in between all the <TD>'s how can the existing coding be reformatted to accomodate the difference from <td>data</td> to <td><span>data</span></td>?
No jQuery please.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#data tr.normal td {
color: #235A81;
background-color: white;
}
#data tr.highlighted td {
color: #FFFFFF;
background-color: #235A81;
}
</style>
<script type='text/javascript'>
function test() {
var table = document.getElementById("data");
var thead = table.getElementsByTagName("thead")[0];
var tbody = table.getElementsByTagName("tbody")[0];
var ishigh
tbody.onclick = function (e) {
e = e || window.event;
var td = e.target || e.srcElement
var row = td.parentNode;
if (ishigh&&ishigh!=row){
ishigh.className='';
}
row.className = row.className==="highlighted" ? "" : "highlighted";
ishigh=row;
getdata(row)
}
document.onkeydown = function(e){
e = e || event;
var code = e.keyCode, rowslim = table.rows.length - 2, newhigh;
if(code === 38){ //up arraow
newhigh = rowindex(ishigh) - 2;
if(!ishigh || newhigh < 0){return GoTo('data', rowslim);}
return GoTo('data', newhigh);
} else if (code === 40){ //down arrow
newhigh = rowindex(ishigh);
if(!ishigh || newhigh > rowslim){return GoTo('data', 0);}
return GoTo('data', newhigh);
}
}
function GoTo(id,nu){
var obj=document.getElementById(id),
trs=obj.getElementsByTagName('TR');
nu = nu + 1;
if (trs[nu]){
if (ishigh&&ishigh!=trs[nu]){
ishigh.className='';
}
trs[nu].className = trs[nu].className=="highlighted" ? "" : "highlighted";
ishigh=trs[nu];
}
getdata(trs[nu]);
}
function rowindex(row){
var rows = table.rows, i = rows.length;
while(--i > -1){
if(rows[i] === row){return i;}
}
}
function getdata(row) {
document.getElementById('firstname').value = row.cells[0].innerHTML;
document.getElementById('lastname').value = row.cells[1].innerHTML;
document.getElementById('age').value = row.cells[2].innerHTML;
document.getElementById('total').value = row.cells[3].innerHTML;
document.getElementById('discount').value = row.cells[4].innerHTML;
document.getElementById('diff').value = row.cells[5].innerHTML;
find_option('fname',row.cells[0].innerHTML)
}
}//end of nested function
function find_option(id,value) {
var sel = document.getElementById(id)
for (var i = 0; i < sel.length; i++){
//alert(sel.options[i].text+" "+sel.options[i].value)
if (sel.options[i].value == value) {
sel.selectedIndex = i;
return
}
}
}
</script>
</head>
<body>
<table id="data" cellspacing="1" border="1">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>age</th>
<th>total</th>
<th>discount</th>
<th>diff</th>
</tr>
</thead>
<tbody>
<tr>
<td><span>peter</span></td>
<td><span>parker</span></td>
<td><span>28</span></td>
<td><span>9.99</span></td>
<td><span>20.3%</span></td>
<td><span>+3</span></td>
</tr>
<tr>
<td>john</td>
<td>hood</td>
<td>33</td>
<td>19.99</td>
<td>25.1%</td>
<td>-7</td>
</tr>
<tr>
<td>clark</td>
<td>kent</td>
<td>18</td>
<td>15.89</td>
<td>44.2%</td>
<td>-15</td>
</tr>
<tr>
<td>bruce</td>
<td>almighty</td>
<td>45</td>
<td>153.19</td>
<td>44%</td>
<td>+19</td>
</tr>
<tr>
<td>benjamin</td>
<td>evans</td>
<td>56</td>
<td>153.19</td>
<td>23%</td>
<td>+9</td>
</tr>
</tbody>
</table>
<br>
Firstname is:
<input type="text" id="firstname" />
<br>Lastname is:
<input type="text" id="lastname" />
<br>Age is:
<input type="text" id="age" />
<br>Total is:
<input type="text" id="total" />
<br>Discount is:
<input type="text" id="discount" />
<br>Diff is:
<input type="text" id="diff" />
<br>
<input type="button" value="testme" onclick="test()">
<br><br>
<select id="fname">
<option value="bruce">bruce</option>
<option value="clark">clark</option>
<option value="benjamin">benjamin</option>
</select>
</body>
</html>
Change this line:
var row = td.parentNode;
to:
var row = (td.tagName == "DIV") ? td.parentNode.parentNode : td.parentNode;
You can look at the elemet's tag name and determine whether the user has clicked on a TD or a SPAN, then adjust select the element's parent (the TD) if you have a span.
var td = e.target || e.srcElement
alert(td.tagName)
Alternately, you can add a CSS class name to all of your SPANS and then check to see if the selected element has that class name. If it does, it's a SPAN, if it doesn't, it's a TD.
I would also suggest using a DIV, not a SPAN.

Categories