Jquery : how to know which row is selected? - javascript

I have a table with dynamically changing rows items.
Among the rows there is a small button / link for each unit.
Eg
Data1 | LinkButton
Data2 | LinkButton
Data3 | LinkButton
Data4 | LinkButton
Data5 | LinkButton
Data6 | LinkButton
What i want is that when i click on the link button ,i need to know which row is selected?Can any one give me pointers on how that can be done?
You help will be greatly appreciated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link href="css/main.css" type="text/css" media="screen, projection" rel="stylesheet" />
</head>
<body><center>
<div id="message" style="display: none;">
</div>
<div id="waiting" style="display: none;">
Please wait<br />
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
</div>
<form action="" id="searchForm">
<label for="search">Matter Search:</label> <input type="text" name="search" id="search" />
<input type="submit" id="submit" value="Submit" />
Link
</form>
<div id="matterTableDiv" style="display: none;">
List of Matters
<table id="matterTable" border="1">
<thead>
<th>Matter Names</th>
<th>Matter Number</th>
<th>Description</th>
<th></th>
</thead>
<tbody>
</tbody>
</table>
</div>
<div id="matterDetailTableDiv" style="display: none;">
Matter Detail Table
</div>
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#search').focus();
$('#submit').click(function(){
$('#message').hide(200);
$("#matterTableDiv").hide(200);
$("#matterTable tbody").text("");
$('#waiting').show(200);
$('#searchForm').hide(200);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
search : $('#search').val()
},
success : function(data){
if(data.msg == "[]" ){
$('#waiting').hide(200);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(200);
$('#searchForm').show(200);
}
$('#waiting').hide(200);
$('#matterTableDiv').removeClass().addClass((data.error === true) ? 'error' : 'success')
if(data.error == false){
var str = JSON.parse(data.msg);
$("#matterTableDiv").show(200);
//alert("List :" + str.length);
//alert("List :" + str.toString());
$("#matterTable").html();
$.each(str, function(key, value) {
var tblRow =
"<tr>"
//+"<td><a id="+key+" href='#dbID="+value.dbID+"&matID="+value.matterID+">"+value.matterInfoSortName+"</a></td>"
+"<td>"+value.matterInfoSortName+"</td>"
+"<td>"+value.matterInfoMatterNum+"</td>"
+"<td>"+value.matterInfoFileDesc+"</td>"
+"<td><input type='button' value="+value.matterInfoFileDesc+"></td>"
+"</tr>";
$(tblRow).appendTo("#matterTable tbody");
//alert(key + ': ' + value.matterInfoSortName);
});
$("button").live("click",function(){
var row = $(this).closest("tr");
var rowIndex = row.index();
alert(rowIndex);
});
}else{
$('#message').removeClass().addClass('error')
.text('There was an error.').show(200);
}
$('#searchForm').show(200);
if (data.error === true)
$('#searchForm').hide(200);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(200);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(200);
$('#searchForm').show(200);
}
});
return false;
});
});
</script>
</center>
</body>

I know that you ask for the row index, there are users that have given you the answer.
But, usually we need the id of the row, because the id belongs to an id in the database.
In this case, you could use the id of the cell or the button itself.
Example:
<table>
<tr id="Data1"><td>a</td><td>b</td><td>c</td><td><input type="button" value="Data"/></td></tr>
<tr id="Data2"><td>a</td><td>b</td><td>c</td><td><input type="button" value="Data"/></td></tr>
<tr id="Data3"><td>a</td><td>b</td><td>c</td><td><input type="button" value="Data"/></td></tr>
<tr id="Data4"><td>a</td><td>b</td><td>c</td><td><input type="button" value="Data"/></td></tr>
</table>
$("input[type=button]").live("click", function() {
var row = $(this).closest("tr");
var rowId = row.attr("id");
alert(rowId);
});
You have this here:
http://www.jsfiddle.net/dactivo/YD3xy/

You can go from this (the clicked button) in the handler and use .closest() to get the <tr> of the button then grab anything you want from there, for example:
$(".someButton").live("click", function() {
var row = $(this).closest("tr");
var rowIndex = row.index();
});
For a full list of "moving-around" functions like this, check out the Tree Traversal section of the API.

I am guessing you are using...
$('.all_links').click(some_function)
So in that case, you can simply find it from inside some_function like so:
function some_function() {
$(this).parents('tr'); // this will give you the link's row.
}

Related

Record deletion by selecting checkbox works fine on first page of Jquery datatables but not in second page

I am new to jquery datatables ,I tried may solution given in the stackoverflow but nothing works for me
So please suggest me what should i to according to my code(easy and simple solution with explanation).
Problem statement-
i implemented checkbox to delete the multiple records of table,
Jquery Datatable works fine on first page, when i click the check all checkbox on first page it checks all the check box of that page and delete the record but if i am in second page and click check all checkbox then it return to first page, also it will not delete the record if i select the records of two different pages
< script >
//Delete conformation message
/***************************/
//SelectAll checkBox
/****************************/
$(document).ready(function() {
$('#testtable').dataTable();
$('#checkall').click(function() {
if (this.checked) {
$('.delete_checkbox').each(function() {
this.checked = true;
$(this).closest('tr').addClass('removeRow');
});
} else {
$('.delete_checkbox').each(function() {
this.checked = false;
$(this).closest('tr').removeClass('removeRow');
});
}
});
/********************************/
//Select indivisual checkBox
/*******************************/
$('.delete_checkbox').click(function() {
if ($(this).is(':checked')) {
$(this).closest('tr').addClass('removeRow');
} else {
$(this).closest('tr').removeClass('removeRow');
}
});
/*******************************/
//Deletion of Data
/***********************************/
$('#delete_all').click(function() {
var checkbox = $('.delete_checkbox:checked').prop('checked', this.checked);;
if (checkbox.length > 0) {
var result = confirm("Are you sure");
if (result == true) {
var checkbox_valu = [];
$(checkbox).each(function() {
checkbox_valu.push($(this).val());
});
$.ajax({
url: "delete.php",
method: "POST",
data: {
checkbox_id: checkbox_valu
},
success: function() {
$('.removeRow').fadeOut(1500);
location.reload(true)
}
});
} else {
return false;
}
} else {
alert("Select atleast one records");
}
});
/******************************************/
});
<
/script>
<style>.removeRow {
background-color: #FF0000;
color: #FFFFFF;
}
</style>
<html>
<head>
<title>Delete Multiple Records using PHP Ajax with Animated Effect</title>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container">
<br />
<div class="table-responsive">
<h3 align="center">Delete Multiple Records using PHP Ajax with Animated Effect</h3><br />
<div class="table-responsive">
<table id="testtable" class="table table-bordered">
<thead>
<tr>
<th width="10%">
<form method="post" action="">
<input type="checkbox" id="checkall" autocomplete="off" />
<button type="button" id="delete_all" class="btn btn-danger btn-xs">Delete</button>
</form>
</th>
<th width="20%">Name</th>
<th width="38%">Address</th>
<th width="7%">Gender</th>
<th width="25%">Designation</th>
<th width="5%">Age</th>
</tr>
</thead>
<?php
foreach($result as $row)
{
echo '
<tr>
<td>
<input type="checkbox" autocomplete="off" class="delete_checkbox" value="'.$row["id"].'" />
</td>
<td>'.$row["name"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["gender"].'</td>
<td>'.$row["designation"].'</td>
<td>'.$row["age"].'</td>
</tr>
';
}
?>
</table>
</div>
</div>
</div>
</body>
</html>
.
Your page is reloading because your table is inside a form element, and because your action does not have a target the page will just submit to itself. Try
$('#buttonId').click( function(event) {
event.preventDefault();
});
to stop the form submitting the page since you are handling it in JavaScript.
Your function to delete rows does not work on multiple pages because the elements on the other [DataTables] pages do not exist in the DOM. When you click page 2 or whatever, DataTables will redraw the table element to show the new values and the old values are hidden. Paging is just a limit of so many results and DataTables is smart enough to throw that into paging.

Insert only Checkbox Selected Row Values into a MySQL Table

Below JSFiddle link is that of a working form, where submitted form values from dynamic rows gets saved to a mysql table using ajax without any page refresh. The outcome of the form submission (i.e Success or Error) will be shown in a div which has an id 'results' using javascript.
JSFiddle Demo
Form Markup
<form name="names" id="names" method="post" action="">
<div class="container">
<div class="table-responsive">
<button type="button" class="btn btn-success addmore">Add</button>
<button type="button" class="btn btn-danger delete">Remove</button>
<br />
<table id="demo" class="table table-bordered table-condensed table-striped table-hover">
<thead>
<tr>
<th>
<input class="check_all" type="checkbox" onclick="select_all()" />
</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" class="case" />
</td>
<td>
<input class="form-control" type="text" name="fname[]" id="fname_1" required>
</td>
<td>
<input class="form-control" type="text" name="lname[]" id="lname_1" required>
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div id="results"></div>
<div id="results2"></div>
</div>
<!-- ./table-responsive -->
</div>
Javascript for Add/Remove Table Rows, Checkbox Row(s) Selection
$(".delete").on('click', function() {
$('.case:checkbox:checked').parents("tr").remove();
$('.check_all').prop("checked", false);
check();
});
var i = $('table tr').length;
$(".addmore").on('click', function() {
count = $('table tr').length;
var data = "<tr><td><input type='checkbox' class='case'/></td>";
data += "<td><input class='form-control' id='fname_" + i + "' name='fname[]' required/></td>";
data += "<td><input class='form-control' id='lname_" + i + "' name='lname[]' required/></td></tr>";
//alert(data);
$('table').append(data);
row = i;
i++;
});
function select_all() {
$('input[class=case]:checkbox').each(function() {
if ($('input[class=check_all]:checkbox:checked').length == 0) {
$(this).prop("checked", false);
} else {
$(this).prop("checked", true);
}
});
}
function check() {
obj = $('table tr').find('span');
$.each(obj, function(key, value) {
id = value.id;
var selected = $('#' + id).html(key + 1);
});
}
Javascript for Form Submission using Ajax
// form submission through ajax
$(document).ready(function() {
$(function() {
$("#names").on("submit", function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: "savename.php",
data: $(this).serialize(),
success: function(response) {
if (response == "Name creation successfull.") {
$("#results").html('<div class="alert alert-success"><button type="button" class="close">×</button>' + response + '</div><br>');
} else {
$("#results2").html('<div class="alert alert-success"><button type="button" class="close">×</button>' + response + '</div><br>');
}
//timing the alert box to close after 5 seconds
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 2000);
//Adding a click event to the 'x' button to close immediately
$('.alert .close').on("click", function(e) {
$(this).parent().fadeTo(500, 0).slideUp(500);
});
$('#names')[0].reset();
},
error: function(response) {
alert(response);
}
});
});
});
});
What I like to implement is this,
User first selects the rows which he/she wants to insert into the mysql table by selecting the checkbox at the beginning of each row.
After selecting the rows, upon clicking the submit button only those selected row values should be inserted into the mysql table.
Tried to implement this by trying out the solutions from various posts similar to this one on this site but was not successful.
Used the solution provided by the user skobaljic (Thank you very much) in this stackoverflow post. Using this code now am able to post only those form values which are from the selected rows to a mysql table.
Updated JSFiddle Working Demo
Following line is for debugging purpose only, comment out after you are done.
$('.submit_data').text(toPost);
While the code works and gets the job done, am just a novice when it comes to javascript, so need expert opinion to mark this post as solved.

Add rows to dataTables from data source

DataTables spring mvc support
I am using one Weblogic data source, I am ultimately attempting to retrieve one record at a time from the Weblogic data source and then display that record in a data table also one at a time. DataTables.net has an example called "add rows" but it does not accommodate using getting data from data sources. The empty data table displays on the webpage, I can see the query running correctly to the data source however the record is not displaying in the data table.
I included the following in my code:
<script src="<c:url value="/resources/js/jquery.js" />"></script>
<script src="<c:url value="/resources/js/jquery.min.js" />"></script>
<script src="<c:url value="/resources/js/jquery.dataTables.min.js" />"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css"/>
Snippet from CONTROLLER:
#RequestMapping(value = "/locate", method = RequestMethod.GET)
public #ResponseBody NewOrder getModelYearAndVehicleOrder(
#RequestParam(value="modelYear") String modelYear\,
#RequestParam(value="vehicleOrder\") String vehicleOrder\){
if (modelYear\.isEmpty() || vehicleOrder\.isEmpty())
throw new IllegalArgumentException("Try Again!");
NewOrder newOrder;
try {
newOrder= OrderRepo.findNewOrderByModelYearAndVehicleOrder(modelYear, vehicleOrder);
}
catch (Exception e){
#SuppressWarnings("deprecation")
Throwable _e = ExceptionUtils.getCause(e);
throw new ExceptionHandler(
DatabaseMessage.RETRIEVE_ERROR.toString(), _e.getMessage());
}
return newOrder;
}
HTML:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<body>
<h1>Template Spring MVC App</h1>
<form id= "locateVehicle">
<p> Model Year? <input id="modelYear" type="text" th:field="*{modelYear}" /> </p>
<p> Order? <input id="orderNum" type="text" th:field="*{vehicleOrder}" /> </p>
<button onclick="goToDetails()">Locate</button>
</form>
<br></br>
<div class="row">
<div class="col-lg-12">
<table id="list" class="display">
<thead>
<tr>
<th>Model Year</th>
<th>Order #</th>
<th>Model</th>
</tr>
</thead>
<tbody>
<c:forEach var="order" items="${order}" varStatus="loop">
<tr>
<td><c:out value="${order.modelYearNbr}" /></td>
<td><c:out value="${order.vehicleOrderNm}" /></td>
<td><c:out value="${order.model}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
JS:
<script>
$(document).ready( function () {
$('#list').DataTable();
} );
function goToODetails() {
var modelYear = $('#modelYearId').val();
var vehicleOrder = $('#vehicleOrderId').val();
var url = './DataLoader/locate?modelYear=' + modelYear + '&vehicleOrder' + vehicleOrder;
$.get(url,function(result) {
var vehicle = result;
var list = $("#list");
list.append('<tr><td>' + result.modelYearNbr + '</td>' +
'<td>' + result.vehicleOrderNm + '</td>' +
'<td>' + result.model + '</td></tr>');
});
}
</script>
Before I added the data table files I was able to see the record post to the webpage, now it is not posting to the table.
Finally got it working, here is how:
$(document).ready(function() {
var table = $('#orderList').DataTable()
$('#goToOrder').on('click', function() {
var modelYear = $('#modelYearId').val();
var url = './DataLoader/locate?modelYear=' + modelYear;
$.get(url, function(result) {
$(result).each(function( i, object ){
var vehicle = result[i];
table.row.add([
vehicle.modelYear,
vehicle.vehicleOrder,
vehicle.model
]).draw(false)
.nodes()
.to$();
})
})
})
});

deleting the table after rows are deleted

I m trying to delete the table after all the rows deleted but somehow i cant check if table has children after deleting all the rows.
I dont understand why looking for the child elements length doesnt work here ? any suggestions ?
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>table manipulation </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
<script src="..//jquery-2.1.3.min.js"></script>
<script src="table.js" type="text/javascript"></script>
</head>
<body>
<table id = "table1">
<tr id = "1">
<td id = "information1"> i m the first row !</td>
<td><button id = "button1" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
</tr>
<tr id = "2">
<td id = "information2"> i m the second row !</td>
<td><button id = "button2" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
</tr>
<tr id = "3">
<td id = "information3" > i m the third row !</td>
<td><button id = "button3" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
<tr id = "4">
<td id = "information4" > i m the fourth row !</td>
<td><button id = "button4" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td>
</tr>
</table>
<div id = "newtable"> </div>
</body>
</html>
var id ;
var table = $('<table></table>').addClass('foo');
function destroy(){
var theParent = document.querySelector("#table1");
var parent = $("#" + id).parent();
$("#" + id).fadeOut( "slow", function() {
$(parent).closest('tr').remove();
alert(theParent.innerHTML);
});
var row = $('<tr</tr>').addClass('bar').text(parent.siblings().html());
table.append(row);
$("#newtable").append(table);
parent.siblings().remove();
theParent.addEventListener("click", doSomething, false);
}
function doSomething(e) {
if($("#table1").children().length < 1 ){
theParent.remove();
}
}
function reply_click(clicked_id)
{
id = clicked_id;
destroy();
}
function doSomething(e) {
if($("#table1 tr").length <= 1 ){
theParent.remove();
}
}
This will help you
You can try this instead:
if($("#table1").find('tr').length < 1 ){
theParent.remove();
}
Browsers will usually add <tbody> and<thead> tags into a table even if they aren't in your HTML, so the rows aren't the only children. The code above just looks for rows.

phonegap changes type of error after every run

why does phone gap changes error after every-time it is compiled.
some times it runs without any error and then the same code gives silly errors such parse error of function not found despite no changes made to the code.
here is the code which gives different errors at each compile
<html>
<head>
<link href="index.css" rel="stylesheet" type="text/css">
<link href="wrapper.css" rel="stylesheet" type="text/css">
<link href="natiweb.css" rel="stylesheet" type="text/css">
<script type="text/javascript" charset="utf-8" src="cordova-2.3.0.js"></script>
<script src="jquery.mobile/jquery-1.7.2.min.js"></script>
<script src="jquery.mobile/jquery.mobile-1.1.0.min.js"></script>
<script type="text/javascript" charset="utf-8">
function loadcontact()
{
alert('load');
// navigator.contacts.find("*",contactSuccess, contactError);
// find all contacts with 'Bob' in any name field
var options = new ContactFindOptions();
options.filter="Bob";
options.multiple=true;
var fields = ["displayName", "name"];
**navigator.contacts.find(fields, contactSuccess onError, options);**
window.location = "download.html";
}
function contactSuccess(contacts)
{
alert('success');
for (var i=0; i<contacts.length; i++)
{
console.log("Display Name = " + contacts[i].displayName);
}
}
function contactError(error)
{
alert('error');
}
</script>
</head>
<body class="index">
<p></p>
<h1 class="natiweb">NatiWeb</h1>
<form name ="choicepage" id="wrapper" >
<table id="wrapper" >
<tr><td>
<table align="center">
<tr></tr>
<p><b>Select Upload/Download</b></p>
<select name="upload/download">
<option selected >Upload</option>
<option>Download</option>
</select>
</td>
</tr>
<tr>
<td><img src="images/contact-icon.png" height="15"> Contacts </td>
<td><input name="opt" type="checkbox" value="Contacts"></td>
</tr>
<tr>
<td><input type="button" value="Back"></td>
<td><input type="submit" value="Next1" onclick="loadcontact();"></td>
</tr>
</table>
</table>
</form>
</body>
</html>
errors 1:SyntaxError: Parse error at file:///android_asset/www/choice.html:22 here line 22 is marked in bold
You have comma missing on that line.
One more thing, you should redirect the user after you receive the success/error callback, not before.
function loadcontact()
{
alert('load');
// navigator.contacts.find("*",contactSuccess, contactError);
// find all contacts with 'Bob' in any name field
var options = new ContactFindOptions();
options.filter="Bob";
options.multiple=true;
var fields = ["displayName", "name"];
navigator.contacts.find(fields, contactSuccess, onError, options);
}
function contactSuccess(contacts)
{
alert('success');
for (var i=0; i<contacts.length; i++)
{
console.log("Display Name = " + contacts[i].displayName);
}
window.location = "download.html";
}
function contactError(error)
{
alert('error');
window.location = "download.html";
}

Categories