将值插入HTML表

时间:2016-04-09 17:14:51

标签: javascript html input html-table

我正在尝试创建一个简单的表,允许用户输入他们的用户名和值,并看到他们的值立即添加到表中。

照片:

enter image description here

当前代码:

   <!doctype html>
<html lang="en">
    <style>
        table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
th, td {
    padding: 15px;
}
    </style>
    <head>
        <meta charset="utf-8">
        <meta name="description" content="page for t1 fantasy sports">
        <title>T1 Fantasy</title>
    </head>
    <body>
        <h1>T1 Fantasy Sports</h1>
        <table style="width=100%">
        <tr>
            <th>Username</th>
            <th>Total Points</th>
            <th>Total Points Yesterday</th>
        </tr>
        <tr>
            <td>nmaron</td>
        </tr>   
        <tr>
            <td>memaron</td>
        </tr>
        <tr>
            <td>youngplum13</td>
        </tr>
        <tr>
            <td>burstometry</td>
        </tr>
        <tr>
            <td>Kermit</td>
        </tr>
        </table>

        <form>
        Username: <br>
            <input type="text" name="username"></br>
        Points Scored: <br>
        <input type="number" name="points"></br>
        <input type="submit" value="Submit">
        </form>
    </body>
</html> 

对此非常陌生。我不想做任何复杂的事情,我需要将用户输入的值放在他们各自的用户名旁边。

2 个答案:

答案 0 :(得分:0)

伪代码(使用Javascript,您可以将其放在文档的头部):

On form submission,  
foundMatch = false;
For each row excluding the headers {,  
  if(the contents of the first <td> == the entered username)  {  
    add a <td> to that row containing the value of the points field  
    and record that you found a match (foundMatch = true).  
    Break out of the iteration unless a duplicate username in the table should also get the score added.
  }  
}  

If you reach the end of the table not having found a match (foundMatch == false), {  
  add a row to the table with the values of the username and points fields.  
}

我只是在这里提供伪代码,以鼓励您更好地理解自己的编码问题,并在未来的问题上投入更多精力。

答案 1 :(得分:0)

对于一个简单的解决方案,你可以使用jquery,这里有你的例子的解决方案plunkr

$(document).ready(function() {
    $("#add-points").submit(function(event) {
    event.preventDefault();
    var username = $("input[name=username]").val();
    var newPoints = parseInt($("input[name=points]").val());

    $("#puntuation tr").each(function(i, row) {
        var $row = $(row);
        var user = $row.find(".playerName").html();
        if(user === username) {
            var $totalPoints = $row.find(".totalPoints");
            var $yesterday = $row.find(".yesterday");
            $yesterday.html($totalPoints.html());
            var currentPoints = $totalPoints.html();
            if(currentPoints) {
                $totalPoints.html(parseInt(currentPoints)+newPoints); 
            } else {
                $totalPoints.html(newPoints);
            }
        }
    });
    });
});