2012-11-13 3 views
0

질문의 "총점"과 질문의 각 대답에 대한 텍스트 입력 간의 차이를 계산하고 싶습니다. 또한 질문에 단 하나의 대답 만있는 경우 텍스트 입력을 읽기 전용으로 표시하고 텍스트 입력의 해당 질문에 대한 "총표"아래의 숫자와 동일한 값을 표시해야합니다. 이하아래 예제의 차이를 계산하는 방법

Screenshot of table and information on problems

읽기 전용 입력란 필요할 때를 계산을하고 표시해야 현재 JQuery와 변수 : 이하

나는 두 시나리오가 테이블과 기입 문제 나타내는 스크린 샷이다 . 그러나 현재는 작동하지 않습니다. 또한 현재 나는 계산을 할 때 총 표시 수를 "5"로 표시했습니다. 이것은 각 행 내에서 숫자 여야하므로 올바르지 않습니다. 따라서 변수 $sessionMarks이 있어야합니다. 수는 없습니다 아래

$(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); 
}) 
} 
}) 

5.는 데이터베이스에서 각 질문의 내용을 출력하는 쿼리에서 테이블의 코드이며, 다음 테이블에 표시합니다

<?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> 

데이터베이스 테이블이

세션 테이블 (이 스크린 샷에있는 것과 동일한 데이터를 따를 것이다) 모습입니다 : ((WHE : 시험 세부 사항은 질문 표

SessionId SessionName 
1   AAA 

)에 저장되는 경우 각 시험의 각 질문)

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

Individual_Answer 표에 대한 (상점 답변 : 각 시험에 대한 질문)

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

응답 표를 저장하는 재 (저장 각각의 마크를 각 개인에 대한 대답)

AnswerId AnswerMarks 
1   2 
2   2 
3   1 
4   5 
+0

Google에 HTML을 제공 할 데이터베이스가 없기 때문에 테이블에 HTML 예제와 함께 제공하십시오. –

+0

샘플 HTML을 포함하도록 질문이 업데이트되었습니다. 업데이트 내용을주의 깊게 읽고 무슨 일이 일어나고 있는지 알고 싶습니다. – Manixman

답변

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> 
+0

안녕하세요, 문제는 예, 샘플 HTML에서 작동하지만 어떻게하면 주 코드에서 작동시킬 수 있습니까? html 테이블에 쿼리의 결과를 반향시키는 php를 보여주는 코드). 그것이 제가 가지고있는 문제입니다. 귀하의 jquery 함수가 작동하지만 예제 html (Btw 경우에만 작동합니다. 총 점수를 계산할 때, 예를 들어 총 점수가 '7'(총 점수가 항상 5는 아님) 인 경우 카운트 다운 총 점수 여야합니다. 그 질문에 대해 2와 3의 값을 갖는 두 개의 텍스트 입력, 그리고 나서 '7'- '2'- '3'은 Total Marks가 '2'와 같음을 의미합니다 .. – Manixman

+0

내가 가지고있는 유일한 문제는 샘플에있는 것입니다. HTML을 숨겨진 입력에 넣었습니다. 질문 1에 대해 . 숨겨진 입력을 동적 HTML 데이터에 올바르게 작성해야합니다. 질문마다 숨겨진 입력의 이름을 수정하는 방법을 알고 있습니까? – Manixman

+0

어떻게해야합니까? 너는 쓰고 변화한다. 질문 1의 샘플 HTML에있는 각 텍스트 입력에 대한 동적 HTML 표의 각 클래스에는 해당 질문의 각 텍스트 입력에 대해 'individualMarks q0_mark_0','individualMarks q0_mark_1 ','individualMarks q0_mark_2'의 세 가지 클래스가 있습니다. 그런 다음 샘플 HTML의 2 번 질문에 대해 클래스를 'individualMark q1_mark_0' (으)로 변경합니다. 질문 3과 마찬가지로 'individualMarks q2_mark_0','individualMarks q2_mark_1' 및 'individualMarks q2_mark_2'로 변경합니다. 나는 이것을 역동적 인 html에 포함시키는 것을 알고 싶다. 이해하니? – Manixman

관련 문제