Readonly text input not appearing for single answer - php

I have a jsfiddle here
Please look at Question 2 in the jsfiddle table as that question contains only a single answer.
In the jquery function what I have tried to do it state that if a question only
contains 1 answer, then the text input under the Marks Per Answer
column for that answer should be readonly and display the same value
as the Total Marks Remaining for that question.
Also if you look in the jsfiddle, it states that under Total Marks Remaining column for that single row, it displays the number 5, it should display number 0. As that number 5 in the readonly text input minus the original number for total marks Remaining (which was 5) means that the number under Total Marks Remaining should be 0 for that row.
My question is that what do I need to include in the jquery function in the jsfiddle so that:
if a question has a single answer, that text input is readonly
displays the total marks number in the text input
displays 0 under "Total Marks Remaining" for that row as it should
of perform the calculation between the number in the read only text
input and the original Total Marks Remaining number.
Below is the code for the jquery function:
Jquery:
$(function () {
//alert("here");
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) {
var t_marks = $("[class*=q" + i + "_ans]").html();
//alert(t_marks);
$("[class*=q" + i + "_mark]").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();
//alert(tot_marks);
var ans_t = 0;
$("[class*=q" + questionno + "_mark]").each(function () {
var num = (isNaN(parseInt($(this).val()))) ? 0 : parseInt($(this).val());
ans_t += parseInt(num);
});
ans_t = tot_marks - ans_t;
//alert(ans_t);
//var fixedno = tot_marks;
var ans = (parseInt(ans_t) < 0) ? tot_marks : ans_t;
$(".q" + questionno + "_ans").val(ans);
$(".q" + questionno + "_ans_text").html(ans);
});
}
});​
Below is the dynamic HTML Table:
HTML:
<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='totalmarksth'>Total Marks</th>
<th class='emptyth'></th>
</tr>
</thead>
<tbody>
<?php
$row_span = array_count_values($searchQuestionId);
$prev_ques = '';
foreach($searchQuestionId as $key=>$questionId){
?>
<tr class="questiontd">
<?php
if($questionId != $prev_ques){
?>
<td class="questionnumtd" name="numQuestion" rowspan="<?php echo$row_span[$questionId]?>"><?php echo$questionId?> <input type="hidden" name="q<?php echo$questionId?>_ans_org" class="q<?php echo$questionId?>_ans_org" value="<?php echo$searchMarks[$key]?>"><input type="hidden" name="q<?php echo$questionId?>_ans" class="q<?php echo$questionId?>_ans" value="<?php echo$searchMarks[$key]?>"></td>
<td class="questioncontenttd" rowspan="<?php echo$row_span[$questionId]?>"><?php echo$searchQuestionContent[$key]?> </td>
<?php
}
?>
<td class="answertd" name="answers[]"><?php echo$searchAnswer[$key]?></td>
<td class="answermarkstd">
<input class="individualMarks q<?php echo$questionId?>_mark_0" q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
<?php
if($questionId != $prev_ques){
?>
<td class="totalmarkstd" rowspan="<?php echo$row_span[$questionId]?>"><?php echo$totalMarks[$key]?></td>
<td class="noofmarkstd q<?php echo$questionId?>_ans_text" q_group="1" rowspan="<?php echo$row_span[$questionId]?>"><?php echo"<strong>Marks Remaining:<br/>".$searchMarks[$key]."</strong>"?></td>
<?php
}
?>
</tr>
<?php
$prev_ques = $questionId;
}
?>
</tbody>
</table>

Your disabling loop is only checking the first of the two questions; a classic out-by-one error. Try this:
var questions = $('#markstbl td[class*="_ans"]').length;
questions will now be 2 instead of 1 and both questions will be looped over.

Related

how to filter dates with angular?

I'm building a project with angular and php. I have a "select" option where I choose specific date and it shows me all details in a table, and counting on several things and everything works great. but when I pick a date, i want it to show all results by specific month and not by specific date(for example --> now i choose date like this - '2016-4-15' it will give me all information specific to this date and not by month like i need). can someone please help? in my database the 'date' value is date.
Php query :
$query=" SELECT `description` ,`total_price` , `name`,`supplier_id`,`date` FROM `suppliers`,`expenses`
where `supplier_id` = `refer_supplier_id` ";
Html:
<select ng-model="supplierExpenses.selectedOption" ng-change="setTotals(supplierExpenses)"
ng-options = "item.date for item in supplierExpenses |
unique:'date'" >
<option value="">בחר תאריך</option>
</select>
<div class="table-responsive">
<table class="customer-list table table-striped" >
<thead>
<tr >
<th class="Column-Header">מספר ספק</th>
<th class="Column-Header">שם ספק</th>
<th class="Column-Header">כמות מוצרים שנקנו</th>
<th class="Column-Header">מחיר הוצאה</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in supplierExpenses" ng-if = "item.date == supplierExpenses.selectedOption.date"
>
<td>{{item.supplier_id}}</td>
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{item.total_price}}</td>
</tr>
</tbody>
<tfoot>
<tr class="bg-warning">
<td><font size="6">סה"כ הוצאות</font></td>
<td><font size="6">{{totalExpenses}}</font></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
Controller:
"use strict";
angular.module('dataSystem').controller('supplierExpensesCtrl', function ($scope, $route, $location, $http) {
$http({method:'GET', url:'api/reports-tab/supplier-expenses-by-mounth.php/'})
.then(function(response) {
var arr = JSON.parse(JSON.parse(response.data));
$scope.supplierExpenses = arr;
})
// This will log you the error code and trace, if there is an error.
.catch(function(err) {
console.log('err', err)
});
$scope.totalExpenses = 0;
$scope.setTotals = function(totalItem){
$scope.totalExpenses = 0;
for(var item =0; item< totalItem.length; item++){
// console.log(totalItem[item]);
if (totalItem[item] && (totalItem[item].date == $scope.supplierExpenses.selectedOption.date)){
$scope.totalExpenses += parseInt(totalItem[item].total_price);
}
}
}
});
Hi glad you succeed with the total ^^ I edit my answer with the working solution for the date issue
$http({method:'GET', url:'api/reports-tab/supplier-expenses-by-mounth.php/'})
.then(function(response) {
var arr = JSON.parse(JSON.parse(response.data)), month, date;
for(var i = 0; i< arr.length; i++){
date = new Date(arr[i].date); //we convert the string into javascript date
month = date.getMonth()+1;
if(month.length === 1){
month = '0'+month; //we add a 0 if needed
}
var year = date.getFullYear();
arr[i].date = month+'/'+year; //we use only the month and year
}
$scope.supplierExpenses = arr;
})

I am getting a blank dynamic html table

I am trying to create dynamic html table but the problem is that it is not displaying any data in the table. I know the query is correct because I tested the query in sql and it outputs the data. The problem I have I am guessing is the dynamic html table itself. Below is the code:
JavaScript/JQuery:
//javascript below will perform calculation between adding numbers between text inputs per each question
//answer for each calculation per question is stored under "Total Marks Remaining" Column
/*If a question only has one answer, then the text input under the "Marks Per Answer" column becomes
read only and displays the same number as the total marks under the "Total Marks Remaining" column
for that question*/
$(function() {
//alert("here");
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){
var t_marks = $("[class*=q"+i+"_ans]").html();
//alert(t_marks);
$("[class*=q"+i+"_mark]").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();
//alert(tot_marks);
var ans_t=0;
$("[class*=q"+questionno+"_mark]").each(function(){
var num = (isNaN(parseInt($(this).val())))?0:parseInt($(this).val());
ans_t+=parseInt(num);
});
ans_t=tot_marks-ans_t;
//alert(ans_t);
//var fixedno = tot_marks;
var ans = (parseInt(ans_t)<0)?tot_marks:ans_t;
$(".q"+questionno+"_ans").val(ans);
$(".q"+questionno+"_ans_text").html(ans);
});
}
});
</script>
PHP:
<?php
if (isset($_POST['id'])) {
$_SESSION['id'] = $_POST['id'];
}
$assessment = $_SESSION['id'];
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;
}?>
HTML:
<form id="Marks" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" 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>
<?php
$row_span = array_count_values($searchQuestionId);
$prev_ques = '';
foreach($searchQuestionId as $key=>$questionId){?>
<tbody>
<tr class="questiontd">
<?php
if($questionId != $prev_ques){?>
<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>
<td class="questioncontenttd" rowspan="<?=$row_span[$questionId]?>"><?=$searchQuestionContent[$key]?> </td>
<?php
}else{?>
<td class="questionnumtd" name="numQuestion" ></td>
<td class="questioncontenttd" ></td>
<?php
}?>
<td class="answertd" name="answers[]"><?=$searchAnswer[$key]?></td>
<td class="answermarkstd">
<input class="individualMarks q<?=$questionId?>_mark_0" q_group="1" name="answerMarks[]" id="individualtext" type="text" />
</td>
<?php
if($questionId != $prev_ques){?>
<td class="noofmarkstd q<?=$questionId?>_ans_text" q_group="1" rowspan="<?=$row_span[$questionId]?>"><?=$searchMarks[$key]?></td>
<?php
}else{?>
<td class="noofmarkstd" q_group="1"></td>
<?php
}?>
</tr>
<?php
$prev_ques = $questionId;
}?>
</tbody>
</table>
</form>
Below is the screenshot of what it is displaying:
Below is what the table should display (The Marks per Answer Column contains text inputs for each row)
Below is database design so you can see where the data is coming from:
Session Table: (Where the exam details is stored)
SessionId SessionName
1 AAA
Question Table: (Where questions for each exams are stored)
SessionId QuestionId QuestionContent Total Marks
1 1 Name three features in a ROM 5
1 2 Here is a single answer 5
Answer Table: (Stores answers for each question in each exam)
AnswerId(auto) SessionId QuestionId Answer
1 1 1 A
2 1 1 B
3 1 1 D
4 1 2 True
Individual_Answer Table: (Stores each individual mark for each individual answer)
AnswerId AnswerMarks
1 2
2 2
3 1
4 5
UPDATE:
Looking at my html code, why is it displaying the table like this below:
Check for missing php open tag <?php before include('connect.php');
Also avoid short tags like <?= and replace them with <?php echo
place <tbody> outside the foreach loop
foreach($searchQuestionId as $key=>$questionId){
?>
<tbody>
to
</thead>
<tbody>
....
....
foreach($searchQuestionId as $key=>$questionId){
?>
Unless there is some code that is not being displayed here, perhaps it's as simple as the $assessment variable not being set, so nothing is being sent to the query?
Also, to confirm that you are actually getting the results back AND binding them OK, I'd be doing a var_dump on the arrays like searchQuestionContent to make sure they have the content you expect in them, if not you know your problem is in the query / binding data. If they do have the content you expect, then you know the problem lies in the table output.

Jquery calculation answer is not correct [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a problem with my calculation answer.
What ever is entered in the text input for each answer in a
question, it will subtract the number under the "Total Marks" column
for that question with the numbers entered within the text input for
that question.
Example is below:
In the text inputs I entered in numbers 1, 1 and 2. The Total Narks under the Total Marks Remaining column was 5 but it is now 1 as 5 - 1 - 1 - 2 = 1 Total Mark Remaining
The problem I have though is that if I change the top text input to lets say 3, then the calculation should now be 5 - 3 - 1 - 2 = -1 Total Mark Remaining. But it doesn't do this as that somewhere in the jquery function it has stated that if Total Marks Remaining number is less than 0, then display the original Total Marks Remaining number which is 5. This is incorrect, it should just display the minus number so the user knows that they need to reduce 1 mark. How can I get the minus number to be displayed if the Total Marks Remaining number is less than 0?
Below is the code for the jquery function:
Jquery:
$(function () {
//alert("here");
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) {
var t_marks = $("[class*=q" + i + "_ans]").html();
//alert(t_marks);
$("[class*=q" + i + "_mark]").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();
//alert(tot_marks);
var ans_t = 0;
$("[class*=q" + questionno + "_mark]").each(function () {
var num = (isNaN(parseInt($(this).val()))) ? 0 : parseInt($(this).val());
ans_t += parseInt(num);
});
ans_t = tot_marks - ans_t;
//alert(ans_t);
//var fixedno = tot_marks;
var ans = (parseInt(ans_t) < 0) ? tot_marks : ans_t;
$(".q" + questionno + "_ans").val(ans);
$(".q" + questionno + "_ans_text").html(ans);
});
}
});​
Below is the dynamic HTML Table:
HTML:
<body>
<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 Remaining</th>
</tr>
</thead>
<tbody>
<?php
$row_span = array_count_values($searchQuestionId);
$prev_ques = '';
foreach ($searchQuestionId as $key => $questionId) {
?>
<tr class="questiontd">
<?php
if ($questionId != $prev_ques) {
?>
<td class="questionnumtd" name="numQuestion" rowspan=
"<?php echo $row_span[$questionId]; ?>"><?php
echo $questionId;
?><input type="hidden" name="q<?php echo $questionId; ?>_ans_org" class=
"q<?php echo $questionId; ?>_ans_org" value=
"<?php echo $searchMarks[$key]; ?>" /><input type="hidden" name=
"q<?php echo $questionId; ?>_ans" class=
"q<?php echo $questionId; ?>_ans" value=
"<?php echo $searchMarks[$key]; ?>" /></td>
<td class="questioncontenttd" rowspan="<?php echo $row_span[$questionId]; ?>">
<?php
echo $searchQuestionContent[$key];
?></td><?php
}
?>
<td class="answertd" name="answers[]"><?php
echo $searchAnswer[$key];
?></td>
<td class="answermarkstd"><input class=
"individualMarks q<?php echo $questionId; ?>_mark_0" q_group="1" name=
"answerMarks[]" id="individualtext" type="text" /></td><?php
if ($questionId != $prev_ques) {
?>
<td class="noofmarkstd q<?php echo $questionId; ?>_ans_text" q_group="1"
rowspan="<?php echo $row_span[$questionId]; ?>"><?php
echo $searchMarks[$key];
?></td><?php
}
?>
</tr><?php
$prev_ques = $questionId;
}
?>
</tbody>
</table>
</body>
</html>
This line is the culprit:
var ans = (parseInt(ans_t) < 0) ? tot_marks : ans_t;
Change it to:
var ans = ans_t;

How to calculate the difference in example below

I want to calculate difference between the "Total Marks" in a question, and the text inputs for each answer in a question. Also if a question has only one answer, then it should display the text input as a readonly and display the same value as the number under the "Total Mark" for that question in that text input.
Below is a screenshot which shows the table and the written problem I have with both scenarios:
Below is the current jquery variable which should be doing the calculation and display the readonly textbox when necessary. But at the moment it is not working. Also at the moment I have display the number for total marks to be fixed as "5" when doing the calculations, well this is incorrect as that it should be the number for within each row, so I believe the variable $sessionMarks that should be the number, not 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);
})
}
})
Below is the code for the table, from the query it outputs the details of each question from the database and then it displays it in a table:
<?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>
Update:
In the sample HTML which is in this fiddle, I can get it to work (except I want the calculation to be total marks minus number entered in text input, not what it is doing now which is when I enter a number in text input it performs an addition from 0 to whatever number entered in text input), but when I tried to edit the code above to do the same thing, then it doesn't work, nothing happens.
The sample html is below:
<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>
Below is what the database tables looks like, (this will follow the same data as the ones in the screenshot)
Session Table: (Where the exam details is stored)
SessionId SessionName
1 AAA
Question Table: (Where questions for each exams are stored)
SessionId QuestionId QuestionContent Total Marks
1 1 Name three features in a ROM 5
1 2 Here is a single answer 5
Answer Table: (Stores answers for each question in each exam)
AnswerId(auto) SessionId QuestionId Answer
1 1 1 A
2 1 1 B
3 1 1 D
4 1 2 True
Individual_Answer Table: (Stores each individual mark for each individual answer)
AnswerId AnswerMarks
1 2
2 2
3 1
4 5
It is not good practice to get and put values from html elements using html() which somehow belong to calculation or integers values, Therefore always use hidden fields for this type of problems, like I have included two hidden fields one for original value and one for the final value and at the end you can get the total marks values easily from the hidden field.
The code is updated for dynamic data. Use your own code for queries, mine is a rough code.
<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>

Calling a JS scipt to run a php file and then post html to the relative row

Follow this if you can...
Basically i have an order form (which begins with one row).
<form id="orderform" name"orderForm" action="/secure/delivery-details.html" method="post">
<a id="add">+</a>
<table id="ordertable" width="533" border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td width="33%">Product Code (e.g 66203)</td>
<td width="33%">Mtrs Required (e.g 10)</td>
<td width="33%">Preview Image</td>
</tr>
<tr class="item">
<td class="prodcode"><input type="text" name="prodcode[]" id="prodcode" /></td>
<td class="meterage"><input type="text" name="meterage[]" id="meterage" /></td>
<td class="imgsample"></td>
</tr>
</tbody>
</table>
<button>Submit</button>
</form>
Notice the link with an ID of "add". When checked this adds a new row to the table with the same ID. Using the code below.
var counter = 0;
//Order Form
$("#add").click(function() {
counter++;
var cln = $('#ordertable tbody>tr:last').clone(true);
// cln.find("[id^='prodcode']").each(function(i, val) {
// val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
// });
cln.insertAfter('#ordertable tbody>tr:last');
$('#ordertable tbody>tr:last input').val('');
$('td.imgsample:last a').remove();
return false;
});
//Check for image preview
$("#prodcode").blur(function() {
var $this = $(this);
$this
.closest('tr') // find the parent tr
.find('td.imgsample') // find the imgsample in the row
.html( $(this).attr('id')) // update the contents
//.animate({'opacity':1},200);
var imgsample = $this.closest('tr').find('td.imgsample')
$.post('/public/themes/lbd/js/searchimage.php', //this page reads the image code and gives you the image location
{ action: 'searchimage', imgreference: $(this).val() },
function(data) {imgsample.html(data);}
);
});
My PHP in searchimage...
When i currently enter a product code if it is invalid it only puts the productID in td.imsample and i want it to say INVALID CODE
//Find image based on Product Code
function findimage($imageToFind) {
require '../../../../config.php';
$dbh = new PDO(DB_DSN, DB_USER, DB_PASS);
$sql = "SELECT * FROM isproducts WHERE prodCode = ".strtoupper($imageToFind)."";
$stmt = $dbh->query($sql);
$obj = $stmt->fetch(PDO::FETCH_OBJ);
$count = $stmt->rowCount();
if($count > 0) {
$sql2 = "SELECT * FROM imageindex WHERE filename LIKE '".strtoupper($imageToFind)."-%'";
$stmt2 = $dbh->query($sql2);
$obj2 = $stmt2->fetch(PDO::FETCH_OBJ);
echo ($stmt2->rowCount() == 1 ? '<span>'.$obj2->path.'/'.$obj2->filename.'</span> -' : 'No Image Available');
} else {
echo 'Invalid Code';
}
}
//Call Function
findimage($_POST['imgreference']);
try this, can have code errors since I could not test at all:
jQuery Template
HTML:
<script id="template-item" type="text/x-jquery-tmpl">
<tr class="item" id="${id}">
<td class="prodcode"><input type="text" name="prodcode[]" class="prodcode-input" data="${id}" val="" /></td>
<td class="meterage"><input type="text" name="meterage[]" class="meterage-input" val="" /></td>
</tr>
</script>
<form id="orderform" name"orderForm" action="/secure/delivery-details.html" method="post">
+
<table id="ordertable" width="533" border="0" cellspacing="0" cellpadding="2">
<thead>
<tr>
<th width="33%">Product Code (e.g 66203)</th>
<th width="33%">Mtrs Required (e.g 10)</th>
<th width="33%">Preview Image</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<td class="imgsample"></td>
</tfoot>
</table>
<button>Submit</button>
</form>
JS:
$(function() {
var counter = 0;
//Check for image preview
var blur_event = function(ev) {
var
self = $(this),
imgsample = $("#ordertable tfoot .imgsample");
$(imgsample).html( $(this).class() ); // update the contents
$.post('/public/themes/lbd/js/searchimage.php', //this page reads the image code and gives you the image location
{ action: 'searchimage', imgreference: $(self).val() },
function(data) {
$(imgsample).html(data);
}
);
return false;
};
//Order Form
$("#add").bind("click", function(ev) {
counter++;
var cln = $('#template-item').tmpl({id:"item-"+counter);
// cln.find("[id^='prodcode']").each(function(i, val) {
// val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
// });
$(cln).find(".prodcode-input").bind("blur", blur_event);
$(cln).appendTo('#ordertable tbody');
return false;
});
});
Your problem is most likely due to the duplicated ID. That makes your HTML document invalid. See my explanation here.

Categories