如何计算下面示例中的差异

时间:2012-11-13 17:38:19

标签: php javascript jquery html

我想计算问题中“总标记”与问题中每个答案的文本输入之间的差异。此外,如果一个问题只有一个答案,那么它应该将文本输入显示为只读,并显示与该文本输入中该问题的“总标记”下的数字相同的值。

下面是一个屏幕截图,显示了我在两种情况下的表格和书面问题:

Screenshot of table and information on problems

下面是当前的jquery变量,它应该进行计算并在必要时显示只读文本框。但目前它不起作用。此外,我在进行计算时显示总标记的数字固定为“5”,这是不正确的,因为它应该是每行内的数字,所以我相信变量$sessionMarks应该是数字,而不是5。

$(function(){             
var questions = $('#markstbl td[class*="_ans"]').length-1;

//disable single entry
for (var i=0;i<=questions;i++){   
if($("[class*=q"+i+"_mark]").length ==1){
$("[class*=q"+i+"_mark]").attr("disabled","disabled")
}                    
}

//find each question set and add listeners
for (var i=0;i<=questions;i++){                                     
$('input[class*="q'+i+'"]').keyup(function(){
var cl = $(this).attr('class').split(" ")[1]
var questionno = cl.substring(cl.indexOf('q')+1,cl.indexOf('_'))
var t=0;
$("[class*=q"+questionno+"_mark]").each(function(){
var num = (isNaN(parseInt($(this).val())))?0:parseInt($(this).val());
t+=parseInt(num);                             
})   
var fixedno = 5;
$(".q"+questionno+"_ans").text((t>fixedno)?fixedno:t);
})
}
})

下面是表格的代码,从查询中输出数据库中每个问题的详细信息,然后将其显示在表格中:

<?php

$assessment = $_SESSION['id'] . $sessionConcat;

include('connect.php');

   $query = "SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionContent, an.Answer, q.QuestionMarks 
   FROM Session s 
   INNER JOIN Question q ON s.SessionId = q.SessionId
   JOIN Answer an ON q.QuestionId = an.QuestionId AND an.SessionId = q.SessionId
   WHERE s.SessionName = ?
   ORDER BY q.QuestionId, an.Answer
   ";

   // prepare query
   $stmt=$mysqli->prepare($query);
   // You only need to call bind_param once
   $stmt->bind_param("s", $assessment);
   // execute query
   $stmt->execute(); 


       // This will hold the search results
    $searchQuestionId = array();
    $searchQuestionContent = array();
    $searchAnswer = array();
    $searchMarks = array();

    // Fetch the results into an array

   // get result and assign variables (prefix with db)
   $stmt->bind_result($dbSessionId, $dbSessionName, $dbQuestionId, $dbQuestionContent, $dbAnswer, $dbQuestionMarks);
      while ($stmt->fetch()) {
        $searchQuestionId[] = $dbQuestionId;
        $searchQuestionContent[] = $dbQuestionContent;
        $searchAnswer[] = $dbAnswer;
        $searchMarks[] = $dbQuestionMarks;
      } 

?>  

....

<tbody>
<tr>
<?php
$previous_question_id = null;
$rowspans = array_count_values($searchQuestionId);
$output = "";
$questionid = 0; //whole question
$questionno = 0; //part of question
foreach ($searchQuestionContent as $key => $question) {
if ($previous_question_id != $searchQuestionId[$key]){
$questionno=0;
}

// removed logic, not necessary to set empty strings if you're skipping them
$output.= '<tr class="questiontd">' . PHP_EOL;
if ($previous_question_id != $searchQuestionId[$key]) {
$output.= '<td class="questionnumtd" name="numQuestion" rowspan="' . $rowspans[$searchQuestionId[$key]] . '">' . htmlspecialchars($searchQuestionId[$key]) . '</td>' . PHP_EOL;
$output.= '<td class="questioncontenttd q{$questionno++}_mark{$questionid}" rowspan="' . $rowspans[$searchQuestionId[$key]] . '">' . htmlspecialchars($question) . '</td>' . PHP_EOL;
}

$output.= '<td class="answertd" name="answers[]">';
$output.= $searchAnswer[$key];
$output.= '</td>';
$output.= '<td class="answermarkstd"><input class="individualMarks" q_group="1" name="answerMarks[]" id="individualtext" type="text" /></td>' . PHP_EOL;

if ($previous_question_id != $searchQuestionId[$key]) {
$output.= '<td class="noofmarkstd  q{$questionid++}_ans" q_group="1" rowspan="' . $rowspans[$searchQuestionId[$key]] . '">' . htmlspecialchars($searchMarks[$key]) . '</td>' . PHP_EOL;
}

// moved this to the end
if ($previous_question_id != $searchQuestionId[$key]) {
$previous_question_id = $searchQuestionId[$key];
}
}
echo $output;
?>
</tr>
</tbody>

更新

在这个fiddle中的示例HTML中,我可以让它工作(除了我希望计算是总标记减去在文本输入中输入的数字,而不是它现在正在做什么,当我在文本输入中输入一个数字,它执行从0添加到文本输入中输入的任何数字的加法,但是当我尝试编辑上面的代码来执行相同的操作时,它就不起作用,没有任何反应。

示例html如下:

<form id="Marks" action="/u0867587/Mobile_app/individualmarks.php" method="post">

<table border='1' id='markstbl'>
<thead>
<tr>
<th class='questionth'>Question No.</th>
<th class='questionth'>Question</th>
<th class='answerth'>Answer</th>
<th class='answermarksth'>Marks per Answer</th>
<th class='noofmarksth'>Total Marks</th>
</tr>
</thead>
<tbody>

<tr class="questiontd">
<td class="questionnumtd" name="numQuestion" rowspan="3">1</td>
<td class="questioncontenttd" rowspan="3">Name three features in a ROM</td>
<td class="answertd" name="answers[]">A</td>
<td class="answermarkstd">
<input class="individualMarks q0_mark_0"  q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
<td class="noofmarkstd q0_ans"  q_group="1" rowspan="3">5</td>
</tr>
<tr class="questiontd">
<td class="answertd" name="answers[]">B</td>
<td class="answermarkstd">
<input class="individualMarks q0_mark_1" q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
</tr>
<tr class="questiontd">
<td class="answertd" name="answers[]">D</td>
<td class="answermarkstd">
<input class="individualMarks q0_mark_2" q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
</tr>
<tr class="questiontd">
<td class="questionnumtd" name="numQuestion" rowspan="1">2</td>
<td class="questioncontenttd" rowspan="1">Here is a single answer</td>
<td class="answertd" name="answers[]">True</td>
<td class="answermarkstd">
<input class="individualMarks q1_mark_0" q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
<td class="noofmarkstd q1_ans" q_group="1" rowspan="1">5</td>
</tr>
</tbody>
</table>
</form>

以下是数据库表的外观(这将遵循与屏幕截图中相同的数据)

会话表:(存储考试详情的地方)

SessionId  SessionName
1          AAA

问题表:(存储每项考试的问题)

SessionId   QuestionId       QuestionContent                Total Marks
1                 1          Name three features in a ROM        5 
1                 2          Here is a single answer             5     

答案表:(在每次考试中存储每个问题的答案)

AnswerId(auto)  SessionId QuestionId  Answer
1               1         1           A
2               1         1           B
3               1         1           D
4               1         2           True

Individual_Answer表:(为每个答案存储每个单独的标记)

AnswerId   AnswerMarks
1          2
2          2
3          1
4          5

1 个答案:

答案 0 :(得分:1)

使用html()以某种方式属于计算或整数值来获取和放置来自html元素的值是不太好的做法。因此,总是使用隐藏字段来解决这类问题,比如我已经包含两个隐藏字段值和一个最终值,最后您可以从隐藏字段轻松获得总标记值。

针对动态数据更新代码。使用您自己的代码进行查询,我的代码很粗糙。

        <html>
    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(function() {           
                var questions = $('#markstbl td[class*="_ans"]').length;

                //disable single entry
                for (var i=1;i<=questions;i++){   
                    if($("[class*=q"+i+"_marks]").length ==1){
                        var t_marks = $("[class*=q"+i+"_ans]").html();
                        alert(t_marks);
                        $("[class*=q"+i+"_marks]").val(t_marks).attr("disabled","disabled");
                        //$("[class*=q"+i+"_mark]").attr("disabled","disabled");
                    }                    
                }

                //find each question set and add listeners
                for (var i=0;i<=questions;i++){                                     
                    $('input[class*="q'+i+'"]').keyup(function(){
                        var cl = $(this).attr('class').split(" ")[1]
                        var questionno = cl.substring(cl.indexOf('q')+1,cl.indexOf('_'));
                        var tot_marks = $(".q"+questionno+"_ans_org").val();

                        var ans_t=0;
                        $("[class*=q"+questionno+"_marks]").each(function(){
                            var num = (isNaN(parseInt($(this).val())))?0:parseInt($(this).val());
                            ans_t+=parseInt(num);                             
                        });
                        ans_t=tot_marks-ans_t;                             

                        var ans = (parseInt(ans_t)<0)?tot_marks:ans_t;
                        $(".q"+questionno+"_ans").val(ans);
                        $(".q"+questionno+"_ans_text").html(ans);
                    });
                }
            });
        </script>
    </head>
<body>
<form id="Marks" action="/u0867587/Mobile_app/individualmarks.php" method="post">
    <?php
    $ident = mysqli_connect('localhost','root','');
    mysqli_select_db($ident,'testdata');

    $query = "SELECT q.SessionId, s.SessionName, q.QuestionId, q.QuestionContent, an.Answer, q.QuestionMarks 
    FROM session s 
    INNER JOIN question q ON s.SessionId = q.SessionId
    JOIN answer an ON q.QuestionId = an.QuestionId AND an.SessionId = q.SessionId
    ORDER BY q.QuestionId, an.Answer
    ";

    $res = mysqli_query($ident,$query);
    $searchQuestionId = array();
    $searchQuestionContent = array();
    $searchAnswer = array();
    $searchMarks = array();

   while ($row = mysqli_fetch_array($res)) {
        $searchQuestionId[] = $row['QuestionId'];
        $searchQuestionContent[] = $row['QuestionContent'];
        $searchAnswer[] = $row['Answer'];
        $searchMarks[] = $row['QuestionMarks'];

    } 

?>  


<form id="Marks" action="/u0867587/Mobile_app/individualmarks.php" method="post">

<table border='1' id='markstbl'>
<thead>
<tr>
<th class='questionth'>Question No.</th>
<th class='questionth'>Question</th>
<th class='answerth'>Answer</th>
<th class='answermarksth'>Marks per Answer</th>
<th class='noofmarksth'>Total Marks</th>
</tr>
</thead>
<tbody>
<?php
$row_span = array_count_values($searchQuestionId);
$output = '';
$rowCount = 1;
$newQuest_id = true;

foreach($searchQuestionId as $key=>$questionId){

    if($newQuest_id == true){

        $output.= '<tr class="questiontd">';
        $output.= '<td class="questionnumtd" name="numQuestion" rowspan="'.$row_span[$questionId].'">'.$questionId.' <input type="hidden" name="q'.$questionId.'_ans_org" class="q'.$questionId.'_ans_org" value="'.$searchMarks[$key].'"><input type="hidden" name="q'.$questionId.'_ans" class="q'.$questionId.'_ans" value="'.$searchMarks[$key].'"></td>';
        $output.= '<td class="questioncontenttd" rowspan="'.$row_span[$questionId].'">'.$searchQuestionContent[$key].' </td>';
    }

    $output.= '<td class="answertd" name="answers[]">'.$searchAnswer[$key].'</td>';
    $output.= '<td class="answermarkstd">';
    $output.= '<input class="individualMarks q'.$questionId.'_marks"  q_group="1" name="answerMarks[]" id="individualtext" type="text" />';
    $output.= '</td>';


    if($newQuest_id == true){
        $output.= '<td class="noofmarkstd q'.$questionId.'_ans_text"  q_group="1" rowspan="'.$row_span[$questionId].'">'.$searchMarks[$key].'</td>';
        $newQuest_id = false;
    }
    $output.= '</tr>';

    if($row_span[$questionId] == $rowCount){
        $newQuest_id = true;
    }

    $rowCount++;
}

echo $output;
?>
</tbody>
</table>
</form>
</form>
</body>
</html>