Click here to Skip to main content
15,882,388 members
Please Sign up or sign in to vote.
1.80/5 (3 votes)
See more:
i want to select each table row. i got a solution yesterday. it work fine with my html but it not work when i add data from mysql by php.below is my code.

1. index.php

XML
<html>
<head><title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
<script>
    $(document).ready(function(){
        var id=0;
        $("table#dataTable").on('click',function(){
                var rows = $('tr').not(':first');
                rows.on('click', function(e) {
                    var row = $(this);
                    id = row.attr('id');
                    if ((e.ctrlKey || e.metaKey) || e.shiftKey) {
                        row.addClass('highlight');
                    } else {
                        rows.removeClass('highlight');
                        row.addClass('highlight');
                    }
                });
                $(document).bind('selectstart dragstart', function(e) {
                    e.preventDefault(); return false;
                });
        });
        $('#button').on('click',function(){
                if(id==''){
                    alert('please select item to display!');
                    return false;
                }else{
                    var r=confirm("You have select row id: "+id);
                    if(r==true){
                        window.location.reload(true);
                    }else{
                        return false;
                    }
                }
            });
    });
    function getId(str) {
      var qty=$('input[name=calc_result]').val();
      if (str=="") {
        document.getElementById("addRow").innerHTML="";
        return;
      }
      if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
      } else { // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
          document.getElementById("addRow").innerHTML=xmlhttp.responseText;
        }
      };
      xmlhttp.open("POST","query.php?id="+str,true);
      xmlhttp.send();
      //window.location.reload(true);
    }
</script>
</head>
<body>
<input id="button" type="button" value="click" />
<INPUT id="1" type="button" value="id 1" onclick="getId(this.id)" />
<INPUT id="2" type="button" value="id 2" onclick="getId(this.id)" />
<INPUT id="3" type="button" value="id 3" onclick="getId(this.id)" />
<div class="addRow" id="addRow">
    <table id="dataTable" class="rounded-corner">
        <tr id="1">
            <th>Id</th>
            <th>Name</th>
            <th>Age</th>
            <th>Salary</th>
        </tr>
    </table>
</div>
</body>
</html>


2. query.php

PHP
<?php
$con = mysqli_connect('localhost','root','','test');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}else{
    echo 'Connection Success!';
}
$id='';
if(isset($_GET['id'])){
    $id=$_GET['id'];
}
$result=mysqli_query($con,"SELECT * FROM employee WHERE id=".$id);
$row=mysqli_fetch_array($result);
    $id=$row['id'];
    $name=$row['name'];
    $age=$row['age'];
    $salary=$row['salary'];

mysqli_query($con,"INSERT INTO employee_temp VALUES('$id','$name','$age','$salary')");

$rs=mysqli_query($con,"SELECT * FROM employee_temp");
echo '<table id="dataTable" class="rounded-corner">';
echo '<tr>';
echo '<th>ID</th><th>Name</th><th>Age</th><th>Salary</th>';
echo '</tr>';
while($row=mysqli_fetch_array($rs)){
    echo '<tr>';
    echo '<td>'.$row['id'].'</td>';
    echo '<td>'.$row['name'].'</td>';
    echo '<td>'.$row['age'].'</td>';
    echo '<td>'.$row['salary'].'</td>';
    echo '</tr>';
}
echo '</table>';
?>


3. mysql table

SQL
CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET latin1 */;

USE `test`;

/*Table structure for table `employee` */

DROP TABLE IF EXISTS `employee`;

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(25) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `salary` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

/*Data for the table `employee` */

insert  into `employee`(`id`,`name`,`age`,`salary`) values (1,'andra',24,200),(2,'alex',26,500),(3,'soki',23,200),(4,'akita',30,1500),(5,'mosny',28,1000),(6,'jamola',27,1000);

/*Table structure for table `employee_temp` */

DROP TABLE IF EXISTS `employee_temp`;

CREATE TABLE `employee_temp` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(25) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `salary` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
Posted
Comments
Mohibur Rashid 1-Jul-14 23:25pm    
not a good way of asking question.

1 solution

This is a common mistake in jQuery, and difficult to identify. As you stated, it worked fine with static HTML, but now that you are building the HTML dynamically it doesn't work.

The problem is your on() event handler. At the time this code is run:
JavaScript
var rows = $('tr').not(':first');
rows.on('click', function(e) { ... });

you haven't added any rows to the table yet.

You need to use a delegated event handler to act on descendants of an existing element, whether or not they exist at the time the event handler is declared.
JavaScript
$('table#dataTable').on('click', 'tr:gt(0)', function(e) { ... });
 
Share this answer
 
Comments
chantholcode 2-Jul-14 21:29pm    
thank for your reply! i have try the above code but it still not work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900