简体   繁体   中英

How to choose only one row at a time in html table using javascript

I want to choose only one row at a time from html table... Im using php,html and javascript.. if i choose one row means that the value only show in alert box at a time using javascript.. I wrote some js coding but it shows all the row values one by one in alertbox.. Please anyone help for me..

My html code:

 <table BORDER="5"> <tr> <th colspan="10"> </th> </tr> <tr> <th>Date & Time</th> <th>Name</th> <th>Source</th> <th>Destination</th> <th>Ride Type</th> <th>Vehicle Type</th> <th>Plate No.</th> <th>Distance</th> </tr> <?php $search_data = "";?> <tbody id="table"style="cursor:pointer"onclick="found(this);"> <tr id="choose"> <?php echo $search_data; ?> </tr> </tbody> </table> 

My javascript:

 function found(row) { //alert("hai"); var table=document.getElementById("table"); var cells = table.getElementsByTagName("tr"); for (var i = 0; i < cells.length; i++) { alert(cells[i].innerHTML); } } 

My php code: while ($data = mysql_fetch_array($firstattempt)) {

        $search_data = "";
       $search_data .= "<tr>";
            $search_data .= "<td>{$data["DATE"]} & {$data["START_TIME"]}</td>";
            $search_data .= "<td>{$data["NAME"]}</td>";             
            $search_data .= "<td>{$data["START_FROM"]}</td>";
            $search_data .= "<td>{$data["END_TO"]}</td>";
            $search_data .= "<td>{$data["RIDER_FLAG"]}</td>";
            $search_data .= "<td>{$data["VEHICLE_TYPE"]}</td>";
            $search_data .= "<td>{$data["PLATE_NO"]}</td>";
            $search_data .= "<td>{$distance} Km</td>";

            $search_data .= "</tr>";
            echo $search_data;

  }

My output : 输出

 function found(row) { //alert("hai"); var table=document.getElementById("table"); var cells = table.getElementsByTagName("tr"); for (var i = 0; i < cells.length; i++) { alert(cells[i].innerHTML); } } 

The for loop is what's showing all the tr's 1 by 1. If you want to only alert 1, remove the for loop and just use the alert sentence, and place a number instead of an i

alert(cells[0].innerHTML);

Would show the first element for example.

try below js:

function fount(row) {
    var tr = row.getElementsByTagName('tr');

    for (var i = 0; i< tr.length; i++) {
        tr[i].onclick = function() {
            alert(this.innerHTML);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM