使用jquery计算提取数据的两个输入值

Calculate two input values of fetched data using jquery

本文关键字:两个 输入 计算 jquery 提取 数据 使用      更新时间:2023-10-25

下面的代码根据下拉选择在输入框中显示一个数据表。然后我想将第1行和第2行的值相乘,并且应该显示在第3行中。但是使用jQuery无法在row1和row2之间进行计算。需要帮助!

display.php

<!DOCTYPE html>
<html lang="en">
<head>
<link href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
    <script type="text/javascript">
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        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("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","ajax.php?q="+str,true);
        xmlhttp.send();
    }
}
$(document).ready(function() {
    $('#form').on('keyup', '.test1', calcTotal) ;
    $('#form').on('keyup', '.test2', calcTotal) ;
    function calcTotal() {
        var $row2 = $(this).closest('tr'),
        test_row  = $row2.find('.test1').val(),
        test_row2 = $row2.find('.test2').val(), 
        total     = test_row * test_row2;
        $row2.find('.test3').val(total);
    }
});
</script>
</head>
<body>
<form name="form_name" method="post" id="form_name" action="" >
<select name="select_name" id="select_name" onchange="showUser(this.value)">
<option value="22">22</option><option value="33">33</option></select>
<div id="txtHint"></div>
</form>
</body>
</html>

ajax.php

<?php
$q = $_GET['q'];
include('connection.php');
$sql="SELECT * from clients where value='".$q."' ";
$result = mysql_query($sql);
echo "<table id='form'>
<tr>
<th>row1</th>
<th>row2</th>
<th>row3</th>
</tr>";
while($row = mysql_fetch_array($result)) {
    $row1=$row['row1'];
    $row2=$row['row2'];
    $row3=$row['row3'];
    echo "<tr>";
    echo "<td><input type='text' name='test1[]' class='test1' value='$row1' /></td>";
    echo "<td><input type='text' name='test2[]' class='test2' value='$row2' /></td>";
    echo "<td><input type='text' name='test3[]' class='test3' value='$row3'/></td>";
    echo "</tr>";
} 
echo "</table>";
?>

替换这两行

 $('#form').on('keyup', '.test1', calcTotal) ;
 $('#form').on('keyup', '.test2', calcTotal) ;   

有了这个

 $(document).on('keyup', '.test1, .test2', calcTotal) ;

因为#form是在DOM构建之后添加到DOM中的。

我认为

$('#form').on('keyup','.test1',calcTotal) ; 

应该用代替

 $('#form').on('keyup', '#test1', calcTotal) ; 

因为test1是输入的id,而不是类。