For some reasons my javascript form validation does not go through every row in the table.
I created the table with the codes below:
The $usr variable is just a result of another process:
<form name="myForm" action="addAccessories.php" method="post" onsubmit="return validateForm(this);">
<table border="1" id="IT">
<tr>
<th>Barcode<em>*</em></th>
<th>Current stock</th>
</tr>
<?php
for($id=1; $id<=$usr; $id++){
?>
<tr>
<td><input type="hidden" name="id[]" value="<?php echo $id; ?>" />
<input type="text" name="bar_code<?php echo $id; ?>" id="bar_code<?php echo $id; ?>" value="" /></td>
<td><input type="text" name="num_stock<?php echo $id; ?>" value="0" id="num_stock<?php echo $id; ?>"/></td>
<?php
}
?>
<tr>
<td> </td>
<td> <button data-theme="b" input type="submit" name="Submit" value="Submit">Add accessories</button></td>
</tr>
</table>
</form>
The number of rows from this table is: rows = $usr + 1
My validation form codes:
<script type="text/javascript">
function validateForm(){
var errors = [];
for(i = 1; i < document.getElementById("IT").rows.length; i++){
var barcode = document.getElementById('bar_code'+i).value;
var des = document.getElementById('description'+i).value;
var num_stock = document.getElementById('num_stock'+i).value;
if(barcode == null || barcode == ""){
errors[errors.length] = "You must enter barcode.";
}
if(isNaN(num_stock)){
errors[errors.length] = "Current stock must be an integer";
}
if(num_stock < 0){
errors[errors.length] = "Current stock must be a positive number";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
}
function reportErrors(errors){
var msg = "There were some problems...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
This process only validates the 1st row in the table then stop. Can anyone show me what went wrong and how to fix it?
Thank you very much for your help
Your code is making life way more complex than it needs to be. A simpler approach is to just deal with the form controls, e.g. since you are already passing a reference to the form from the submit listener:
function validateForm(form) {
var errors = [];
var c, cs = form.elements;
var reB = /^bar_code/;
var reN = /^num_stock/;
var reD = /^[0-9]+$/;
for (var i=0, iLen=cs.length; i<iLen; i++) {
c = cs[i];
if (reB.test(c.name) && c.value == '') {
errors.push('You must enter barcode.'];
} else if (reN.test(c.name) && !reD.test(c.value)) {
errors.push('Stock number must be a positive integer.'];
}
}
// deal with errors...
}
Note that in the test:
> barcode == null || barcode == ""
barcode is a string, so the first test will never return true and the second is sufficient if you want to see if it's empty.
Related
for (i=0; i < arr.length; i++)
{
var ItemId = arr[i];
var ItemQuantity = OrderedItemNameQuantityPair[ShopIdNamePair[SelectedShopIndex]+"_"+GetShopItems[ItemId]] ;
<?php
if(isset($_SESSION["ItemIdQuantity"]))
{
$ItemIdQuantity= $_POST['ItemId'];
}
else
{
$ItemIdQuantity = 0;
}
?>
ItemtableData=ItemtableData+'<table class="id_td_ItemContent"><tr><td width="40%" class="OrderedItem">'+GetShopItems[ItemId]+'</td>'+'<td width="10%">'+'<input class="OrderedQuantity" type="text" maxlength="2" name="ItemId" value='+ItemId+'></td>'+'<td width="10%">'+'<input class="OrderedQuantity" type="text" maxlength="2" name="Quantity" value='+"<?php print $ItemIdQuantity; ?>"+'></td>'+'<td width="50%" class="AddToOrder">'+'<input type="Button" onClick="updatedata()">'+'</td></tr></table>';
}
I want to get the input field value ItemId and assing it to $ItemIdQuantity variable.
But the code which i used after page refresh output is not coming.
I'm trying to auto submit a form,(below it's only the form, its wrapped with a while{} for each DB entry to display).
It's working for all days of the week, but I can't submit the value for $totalhours, $holidayhours, $wagegross without a js event like onfocus().
Basically I want to submit this 3 inputs without an click or any other manual action.
any idea ?
<form id="weeklysheet" name="weeklysheet" method="post" action="hourly-function.php">
<tbody>
<tr style="line-height:0px;">
<td class="large">
<p class="employee_name"><?php echo $fullname?></p>
</td>
<td class="small">
<input name="mon" id="mon" type="text" class="days_input" value="<?php echo $data['mon'];?>"onchange="this.form.submit();"/>
</td>
<td class="small">
<input name="tue" id="tue" type="text" class="days_input" value="<?php echo $data['tue'];?>"onchange="this.form.submit();"/>
</td>
<td class="small">
<input name="wed" id="wed" type="text" class="days_input" value="<?php echo $data['wed'];?>"onchange="this.form.submit();"/>
</td>
<td class="small">
<input name="thu" id="thu" type="text" class="days_input" value="<?php echo $data['thu'];?>"onchange="this.form.submit();"/>
</td>
<td class="small">
<input name="fri" id="fri" type="text" class="days_input" value="<?php echo $data['fri'];?>"onchange="this.form.submit();"/>
</td>
<td class="small">
<input name="sat" id="sat" type="text" class="days_input" value="<?php echo $data['sat'];?>"onchange="this.form.submit();"/>
</td>
<td class="small">
<input name="sun" id="sun" type="text" class="days_input" value="<?php echo $data['sun'];?>"onchange="this.form.submit();"/>
</td >
<td class="small">
<input name="totalhours" id="totalhours" type="text" class="cumul_week_input" value="<?php echo $totalhours ?>"onfocus="this.form.submit();"/>
</td>
<td class="small">
<input name="holidayhours" type="text" class="cumul_week_input" value="<?php echo $holidayhours ?>"onfocus="this.form.submit();"/>
</td>
<td class="small">
<input name="wagegross" type="text" class="cumul_week_input" value="<?php echo $wagegross ?>"onfocus="this.form.submit();"/>
</td>
<td>
<input type="submit"name="save" id="save" value="Confirm" style="display:none;" />
</tr>
</tbody>
</form>
You could use jQuery to trigger the submit button's click action after the document has loaded like so:
1.) You can link the jQuery library from Google's Hosted Libraries:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
or, download it from jQuery.com to, say a "js" folder, and include it
<script src="js/jQuery.js"></script>
2.) Place this script tag at below the </form> tag:
<script type="text/javascript">
$(document).ready(function(){ //When the document is done loading
$("input#save").trigger('click'); //"Click" on the input button with an ID of "save"
});
</script>
Or you could do it the pure javascript way without jQuery like so:
<html>
<body onLoad="submitform()">
<form id="weeklysheet" name="weeklysheet" method="post" action="hourly-function.php">
Then place this script tag below the </form> tag:
<script type="text/javascript">
function submitform()
{
document.weeklysheet.submit();
}
</script>
Or, to shorten the method above:
<html>
<body onLoad="Javascript: document.weeklysheet.submit();">
<form id="weeklysheet" name="weeklysheet" method="post" action="hourly-function.php">
Are you looking to submit them individually or all at once? If you want to do it all at once you could give the last element an id and in jquery use $('#div').moueleave
that's the js I'm using, I've try submitting with a timeout and it's working.
at the end my issue is not there, it appear that when I'm submit the form, the 3 php variables push the value of the previous input entry.
I don't know if I'm clear with my explanation...
<script type="text/javascript">
function submitform()
{
//document.getElementById("weeklysheet");
var form = document.getElementById("weeklysheet")
form.submit();
}
function submit()
{
if (document.getElementById("weeklysheet")) {
setTimeout("submitform()", 5000); // set timout
}
return false;
}
</script>
(sorry if it's a long explanation)
I'm coming back with my solution... in case that can help anyone.
so the idea it's to have a table that display a list of employees where you can input the days worked, holidays, sick. Then do the sum of each and calculate the gross depending on a wages frequency (i.e: Weekly, 4 Weekly or Monthly).
Because the user won't complete the all form at once, I needed to make the submission automatic for all inputs at all the time of the current week.
this is the JS:
<script type="text/javascript">
function grab<?=$empnum?>(){
// Monday
var mon<?=$empnum?> = document.getElementById('mon<?=$empnum?>').value;
if ((mon<?=$empnum?> == "h" || mon<?=$empnum?> == "H")){
var Hmon<?=$empnum?> = 1;
var Wmon<?=$empnum?> = 0;
var Smon<?=$empnum?> = 0;
}
else if((mon<?=$empnum?> == "w" || mon<?=$empnum?> == "W")){
var Wmon<?=$empnum?> = 1;
var Hmon<?=$empnum?> = 0;
var Smon<?=$empnum?> = 0;
}
else if((mon<?=$empnum?> == "s" || mon<?=$empnum?> == "S")){
var Smon<?=$empnum?> = 1;
var Hmon<?=$empnum?> = 0;
var Wmon<?=$empnum?> = 0;
}
else{
var Smon<?=$empnum?> = 0;
var Hmon<?=$empnum?> = 0;
var Wmon<?=$empnum?> = 0;
var Xmon<?=$empnum?> = 0;
}
// Tuesday
var tue<?=$empnum?> = document.getElementById('tue<?=$empnum?>').value;
if ((tue<?=$empnum?> == "h" || tue<?=$empnum?> == "H")){
var Htue<?=$empnum?> = 1;
var Wtue<?=$empnum?> = 0;
var Stue<?=$empnum?> = 0;
}
else if((tue<?=$empnum?> == "w" || tue<?=$empnum?> == "W")){
var Wtue<?=$empnum?> = 1;
var Htue<?=$empnum?> = 0;
var Stue<?=$empnum?> = 0;
}
else if((tue<?=$empnum?> == "s" || tue<?=$empnum?> == "S")){
var Stue<?=$empnum?> = 1;
var Htue<?=$empnum?> = 0;
var Wtue<?=$empnum?> = 0;
}
else{
var Stue<?=$empnum?> = 0;
var Htue<?=$empnum?> = 0;
var Wtue<?=$empnum?> = 0;
}
// Wednesday
var wed<?=$empnum?> = document.getElementById('wed<?=$empnum?>').value;
if ((wed<?=$empnum?> == "h" || wed<?=$empnum?> == "H")){
var Hwed<?=$empnum?> = 1;
var Wwed<?=$empnum?> = 0;
var Swed<?=$empnum?> = 0;
}
else if((wed<?=$empnum?> == "w" || wed<?=$empnum?> == "W")){
var Wwed<?=$empnum?> = 1;
var Hwed<?=$empnum?> = 0;
var Swed<?=$empnum?> = 0;
}
else if((wed<?=$empnum?> == "s" || wed<?=$empnum?> == "S")){
var Swed<?=$empnum?> = 1;
var Hwed<?=$empnum?> = 0;
var Wwed<?=$empnum?> = 0;
}
else{
var Swed<?=$empnum?> = 0;
var Hwed<?=$empnum?> = 0;
var Wwed<?=$empnum?> = 0;
}
// Thurday
var thu<?=$empnum?> = document.getElementById('thu<?=$empnum?>').value;
if ((thu<?=$empnum?> == "h" || thu<?=$empnum?> == "H")){
var Hthu<?=$empnum?> = 1;
var Wthu<?=$empnum?> = 0;
var Sthu<?=$empnum?> = 0;
}
else if((thu<?=$empnum?> == "w" || thu<?=$empnum?> == "W")){
var Wthu<?=$empnum?> = 1;
var Hthu<?=$empnum?> = 0;
var Sthu<?=$empnum?> = 0;
}
else if((thu<?=$empnum?> == "s" || thu<?=$empnum?> == "S")){
var Sthu<?=$empnum?> = 1;
var Hthu<?=$empnum?> = 0;
var Wthu<?=$empnum?> = 0;
}
else{
var Sthu<?=$empnum?> = 0;
var Hthu<?=$empnum?> = 0;
var Wthu<?=$empnum?> = 0;
}
// Friday
var fri<?=$empnum?> = document.getElementById('fri<?=$empnum?>').value;
if ((fri<?=$empnum?> == "h" || fri<?=$empnum?> == "H")){
var Hfri<?=$empnum?> = 1;
var Wfri<?=$empnum?> = 0;
var Sfri<?=$empnum?> = 0;
}
else if((fri<?=$empnum?> == "w" || fri<?=$empnum?> == "W")){
var Wfri<?=$empnum?> = 1;
var Hfri<?=$empnum?> = 0;
var Sfri<?=$empnum?> = 0;
}
else if((fri<?=$empnum?> == "s" || fri<?=$empnum?> == "S")){
var Sfri<?=$empnum?> = 1;
var Hfri<?=$empnum?> = 0;
var Wfri<?=$empnum?> = 0;
}
else{
var Sfri<?=$empnum?> = 0;
var Hfri<?=$empnum?> = 0;
var Wfri<?=$empnum?> = 0;
}
// Saturday
var sat<?=$empnum?> = document.getElementById('sat<?=$empnum?>').value;
if ((sat<?=$empnum?> == "h" || sat<?=$empnum?> == "H")){
var Hsat<?=$empnum?> = 1;
var Wsat<?=$empnum?> = 0;
var Ssat<?=$empnum?> = 0;
}
else if((sat<?=$empnum?> == "w" || sat<?=$empnum?> == "W")){
var Wsat<?=$empnum?> = 1;
var Hsat<?=$empnum?> = 0;
var Ssat<?=$empnum?> = 0;
}
else if((sat<?=$empnum?> == "s" || sat<?=$empnum?> == "S")){
var Ssat<?=$empnum?> = 1;
var Hsat<?=$empnum?> = 0;
var Wsat<?=$empnum?> = 0;
}
else{
var Ssat<?=$empnum?> = 0;
var Hsat<?=$empnum?> = 0;
var Wsat<?=$empnum?> = 0;
}
// Sunday
var sun<?=$empnum?> = document.getElementById('sun<?=$empnum?>').value;
if ((sun<?=$empnum?> == "h" || sun<?=$empnum?> == "H")){
var Hsun<?=$empnum?> = 1;
var Wsun<?=$empnum?> = 0;
var Ssun<?=$empnum?> = 0;
}
else if((sun<?=$empnum?> == "w" || sun<?=$empnum?> == "W")){
var Wsun<?=$empnum?> = 1;
var Hsun<?=$empnum?> = 0;
var Ssun<?=$empnum?> = 0;
}
else if((sun<?=$empnum?> == "s" || sun<?=$empnum?> == "S")){
var Ssun<?=$empnum?> = 1;
var Hsun<?=$empnum?> = 0;
var Wsun<?=$empnum?> = 0;
}
else{
var Ssun<?=$empnum?> = 0;
var Hsun<?=$empnum?> = 0;
var Wsun<?=$empnum?> = 0;
}
var W<?=$empnum?> = Wmon<?=$empnum?>*1+Wtue<?=$empnum?>*1+Wwed<?=$empnum?>*1+Wthu<?=$empnum?>*1+Wfri<?=$empnum?>*1+Wsat<?=$empnum?>*1+Wsun<?=$empnum?>*1;
var H<?=$empnum?> = Hmon<?=$empnum?>*1+Htue<?=$empnum?>*1+Hwed<?=$empnum?>*1+Hthu<?=$empnum?>*1+Hfri<?=$empnum?>*1+Hsat<?=$empnum?>*1+Hsun<?=$empnum?>*1;
var S<?=$empnum?> = Smon<?=$empnum?>*1+Stue<?=$empnum?>*1+Swed<?=$empnum?>*1+Sthu<?=$empnum?>*1+Sfri<?=$empnum?>*1+Ssat<?=$empnum?>*1+Ssun<?=$empnum?>*1;
var totals<?=$empnum?> = document.getElementById('totalhrs<?=$empnum?>').value = W<?=$empnum?>;
var holiday<?=$empnum?> = document.getElementById('holihrs<?=$empnum?>').value = H<?=$empnum?>;
var sick<?=$empnum?> = document.getElementById('sickdays<?=$empnum?>').value = S<?=$empnum?>;
var wage<?=$empnum?> = document.getElementById('wagefreq<?=$empnum?>').value;
if(wage<?=$empnum?> == 'Weekly'){
document.getElementById('gross<?=$empnum?>').value = <?=$empsalarywage?>;
}
else if(wage<?=$empnum?> == '4 Weekly'){
document.getElementById('gross<?=$empnum?>').value = (<?=$empsalarywage?> / 4);
}
else if(wage<?=$empnum?> == 'Monthly'){
document.getElementById('gross<?=$empnum?>').value = ((<?=$empsalarywage?> * 12) / 52);
}
document.getElementById('weeklysheet<?=$empnum?>').submit('save<?=$empnum?>');
}
</script>
this the form:
<form id="weeklysheet<?=$empnum?>" name="weeklysheet" method="post" action="salary-function.php" >
<tbody>
<tr style="line-height:0px;">
<td class="large">
<p class="employee_name"><?=$fullname?></p>
</td>
<td class="small">
<input name="mon" id="mon<?=$empnum?>" type="text" class="days_input" maxlength="1" value="<?php echo $mon?>"onchange="grab<?=$empnum?>()"/>
</td>
<td class="small">
<input name="tue" id="tue<?=$empnum?>" type="text" class="days_input" maxlength="1" value="<?php echo $tue?>"onchange="grab<?=$empnum?>()"/>
</td>
<td class="small">
<input name="wed" id="wed<?=$empnum?>" type="text" class="days_input" maxlength="1" value="<?php echo $wed?>"onchange="grab<?=$empnum?>()"/>
</td>
<td class="small">
<input name="thu" id="thu<?=$empnum?>" type="text" class="days_input" maxlength="1" value="<?php echo $thu?>"onchange="grab<?=$empnum?>()"/>
</td>
<td class="small">
<input name="fri" id="fri<?=$empnum?>" type="text" class="days_input" maxlength="1" value="<?php echo $fri?>"onchange="grab<?=$empnum?>()"/>
</td>
<td class="small">
<input name="sat" id="sat<?=$empnum?>" type="text" class="days_input" maxlength="1" value="<?php echo $sat?>"onchange="grab<?=$empnum?>()"/>
</td>
<td class="small">
<input name="sun" id="sun<?=$empnum?>" type="text" class="days_input" maxlength="1" value="<?php echo $sun?>"onchange="grab<?=$empnum?>()"/>
</td >
<td class="small">
<input name="totalhrs" id="totalhrs<?=$empnum?>" type="text" class="cumul_week_input" readonly value="<?php echo $totalhrs?>"/>
</td>
<td class="small">
<input name="holihrs" id="holihrs<?=$empnum?>" type="text" class="cumul_week_input" readonly value="<?php echo $holihrs?>"/>
</td>
<td class="small">
<input name="sickdays" id="sickdays<?=$empnum?>" type="text" class="cumul_week_input" readonly value="<?php echo $sickdays?>"/>
</td>
<td class="small">
<input name="gross" id="gross<?=$empnum?>" type="text" class="cumul_week_input" readonly value="<?php echo $gross?>"/>
</td>
<td>
<input type="submit"name="save" id="save<?=$empnum?>" value="Confirm" style="display:none"/>
<input type="hidden"name="enddate" value="<?php echo $data['currentWeekStart']; ?>"/>
<input type="hidden"name="wagefreq"id="wagefreq<?=$empnum?>" value="<?=$wagefreq?>"/>
</td>
</tr>
</tbody>
</form>
that's something that worked like I want, but if anyone see anything that could be done in a better way, I would really apreciate any corrections...
thank's
I have a piece of code below where it determines which assessment the user is in and the assessment number the user is currently on:
<?php echo $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?>
So on the browser this could read for example:
1 OF 4
Now below I have a submit button:
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
Now if the user clicks on the button, it will show a confirmation box and if the user clicks OK, for the confirmation, then it will submit the page and what is suppose to happen is that it adds a number to the assessment to indicate that the user is on the next assessment.
SO FOR EXAMPLE:
If it says this on the page:
1 OF 4
If the user submits the page and confirms, then it should now say this:
2 OF 4
This is because the user is on the next assessment now.
But the problem is that it is not adding the number at all when the user submits the page. It just stays at '1' and doesn't add up. So instead of doing the above it is doing the below:
If it says this on the page:
1 OF 4
If the user submits the page and confirms, then it still says:
1 OF 4
This is obviously incorrect.
I have tested my code and what I have found is that if there is that the jquery validation() is causing the number to not add up and stay at '1'. But my question is that how come this jquery function is causing this to happen?
Below is the jquery validation() function:
function validation() {
var _qid = "";
var _msg = "";
var alertValidation = "";
// Note, this is just so it's declared...
$("tr.optionAndAnswer").each(function() {
});
if (alertValidation != "") {
alert(_msg + alertValidation);
return false;
}
return true;
}
Below is relevant code so you know what the code is:
<?php
session_start();
if(isset($_POST['sessionNum'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = intval($_POST['sessionNum']);
$_SESSION['sessionCount'] = 1;
}
elseif (isset($_POST['submitDetails']) && $_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
$_SESSION['sessionCount']++;
}
$sessionMinus = $_SESSION['sessionCount'];
if ($sessionMinus == $_SESSION['initial_count']){
$action = 'create_session2.php';
}elseif($sessionMinus != $_SESSION['initial_count']){
$action = $_SERVER['PHP_SELF'];
}
?>
<script type="text/javascript">
function validation() {
var _qid = "";
var _msg = "";
var alertValidation = "";
// Note, this is just so it's declared...
$("tr.optionAndAnswer").each(function() {
});
if (alertValidation != "") {
alert(_msg + alertValidation);
return false;
}
return true;
}
function showConfirm(){
var confirmMsg=confirm("Make sure that your details are correct, once you proceed after this stage you would not be able to go back and change any details towards Questions, Options and Answers for your Session." + "\n" + "\n" + "Are you sure you want to Proceed?" + "\n" );
if (confirmMsg==true)
{
submitform();
}
}
function submitform()
{
var fieldvalue = $("#QandA").val();
$.post("insertQuestion.php", $("#QandA").serialize() ,function(data){
var QandAO = document.getElementById("QandA");
QandAO.submit();
});
alert("Your Details for this Session has been submitted");
}
</script>
</head>
<body>
<form id="QandA" action="<?php echo htmlentities($action); ?>" method="post">
<h1><?php echo $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?></h1>
<div id="detailsBlock">
<table id="questionBtn" align="center">
<tr>
<th>
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
</th>
</tr>
</table>
</div>
<hr/>
<div id="details">
<table id="qandatbl" align="center">
<thead>
<tr>
<th class="question">Question</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<p><input id="submitBtn" name="submitDetails" type="submit" value="Submit Details" onClick="myClickHandler(); return false;" /></p>
</form>
<script type="text/javascript">
function myClickHandler(){
if(validation()){
showConfirm();
}
}
</script>
UPDATE:
Below is the code of in the insertQuestion() function:
function insertQuestion(form) {
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'>");
var $image = $("<td class='image'></td>");
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"<p class='imagef1_upload_process' align='center'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p class='imagef1_upload_form' align='center'><br/><label>" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
$image.append($fileImage);
$tr.append($image);
$tbody.append($tr);
}
I think you want to check if sessionCount is NOT set (!isset). Try adjusting your code like this:
if(!isset($_POST['sessionCount'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = intval($_POST['sessionNum']);
$_SESSION['sessionCount'] = 1;
}
elseif (isset($_POST['submitDetails']) && $_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
$_SESSION['sessionCount']++;
}
I have a table with records from a database which is dynamically filled.
<table>
<tr>
<td>name
</td>
<td>surname
</td>
...
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['Name'];?>
</td>
<td><?php echo $row_Recordset1['Surname'];?>
</td>
...
<td align="center">
<form name="form" action="novi.php">
<input name="check" type="radio" value="da">Да
<input name="check" type="radio" value="ne">Не
<input type="hidden" id="id" value="<?php echo $row_Recordset1['id_korisnici'];?>">
<input class="button1"type="button" id="klik" value="Испрати"/>
</form>
</td>
</tr>
<?php } while($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</table>
And than I'm using J Query to create an AJAX call to another page which will run the query.
<script>
$('#klik').click(function() {
var check = $("input[name='check']:checked").val();
var id = $('#id').val();
if (check == "da")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik').prop('value', (data));
document.location.reload();
});
}
else if (check == "ne")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik').prop('value', (data));
document.location.reload();
});
}
else
{
$('#klik').prop('value', 'Грешка');
setTimeout("$('#klik').prop('value', '.')",500);
setTimeout("$('#klik').prop('value', '..')",1000);
setTimeout("$('#klik').prop('value', '...')",1500);
setTimeout("$('#klik').prop('value', 'Испрати')",2000);
}
});
This is working OK if there is only one row in the table.
What I don't know how to do is, to make the script store all the generated CHECKED radio buttons in an array or something, plus all the ID's of the records from the database and send them to another page where according to their ID's a query will update the database..
<?php
if ($_POST['id'] != NULL) {
if ($_POST['check'] == "da") {
$id = mysql_real_escape_string($_POST['id']);
$update = mysql_query("update korisnici set validacija = 1 where id_korisnici= '$id'");
if ($update === true) {
echo 'OK';
}else if ($update === false){
echo 'Error!!!';
}
}
elseif ($_POST['check'] == "ne")
{
$id = mysql_real_escape_string($_POST['id']);
$update = mysql_query("update korisnici set validacija = 2 where id_korisnici= '$id'");
if ($update === true) {
echo 'OK';
}
else if ($update === false){
echo 'Error!!!';
}
}
} else {
echo 'Error!!!';
}
?>
Thanks!
P.S. I'm a noob in JQuery and a beginner in PHP...
UPDATE:
I did change some things. And now the values are shown as I want, when I click the button without a selection I'm getting the error message in the ELSE part of the JQuery code in the proper button. But no matter which button I click (if the table is populated with 3 records from the database, there are 3 buttons) only the first row from the table is updated in the database.
<form name="form" action="novi.php">
<input name="check<?php echo $row_Recordset1['id_korisnici'];?>" type="radio" value="da">Да
<input name="check<?php echo $row_Recordset1['id_korisnici'];?>" type="radio" value="ne">Не
<input type="hidden" id="id" value="<?php echo $row_Recordset1['id_korisnici'];?>">
<input class="button1"type="button" id="klik<?php echo $row_Recordset1['id_korisnici'];?>" value="Испрати"/>
</form>
The JQuery:
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').click(function() {
var check = $("input[name='check<?php echo $row_Recordset1['id_korisnici'];?>']:checked").val();
var id = $('#id').val();
if (check == "da")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', (data));
document.location.reload();
});
}
else if (check == "ne")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', (data));
document.location.reload();
});
}
else
{
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', 'Error');
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '.')",500);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '..')",1000);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '...')",1500);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', 'Send')",2000);
}
});
Make each group of radio buttons have a unique name but the same class. Then you can iterate through them using jQuery:
var radioVals = new Array();
var i = 0;
$(".radioButtonClass:checked").each(function() {
radioVals[i] = $(this).val();
});
Then just pass the array in your ajax call.
I'm trying to create a simple form which calculates the values in every input field which has subtotal at the start of the name attribute:
<script type="text/javascript" src="jq.js"></script>
<script type="text/javascript">
$(function(){
var qty = 0;
var price = 0;
var subtotal = 0;
var qty_r = [];
var price_r = [];
var subs_r = [];
var total = 0;
$('input[name^=qty]').each(function(index) {
qty_r[index] = $(this).val();
});
$('input[name^=price]').each(function(index){
price_r[index] = $(this).val();
});
var j = 0;
for(j = 0; j<=2; j++){
subs_r[j] = parseInt(price_r[j]) * parseInt(qty_r[j]);
}
$('input[name^=subtotal]').each(function(index){
$(this).val(subs_r[index]);
});
$('input[name^=qty]').keyup(function(){
var basis = $(this).attr("id");
var numbasis = basis.toString();
qty = $(this).val();
price = $('input[name=' + numbasis + ']').val();
subtotal = parseInt(qty) * parseInt(price);
$("#subtotal" + numbasis).val(subtotal);
This is the part where I'm having trouble:
$("input[name=subs]").each(function(index){
total = parseInt($(this).val()) + total;
$('#total').val(total);
});
});
});
</script>
And here's where the data which being calculated comes from:
<?php $products = array(array("prodname"=>"mais", "qty"=>5, "price"=>15), array("prodname"=>"strawberry", "qty"=>7, "price"=>25), array("prodname"=>"kambing", "qty"=>14, "price"=>3)); ?>
<table border="1">
<tr>
<th>Product</th>
<th>Qty</th>
<th>Price</th>
<th>Subtotal</th>
</tr>
<?php foreach($products as $key=>$prods){
?>
<tr>
<td><input type="text" name="prodname<?php echo $key; ?>" value="<?php echo $prods['prodname']; ?>"/></td>
<td><input type="text" id="<?php echo $key; ?>" name="qty<?php echo $key; ?>" value="<?php echo $prods['qty']; ?>"/></td>
<td><input type="text" name="<?php echo $key; ?>" id="price<?php echo $key; ?>" value="<?php echo $prods['price']; ?>"/></td>
<td><input type="text" name="subs" id="subtotal<?php echo $key; ?>" /></td>
</tr>
<?php } ?>
</table>
Total: <input type="text" id="total"/><br/>
The problem is that I'm always getting NaN as a result.
If you're getting NaN you're probably trying to parseInt something that has a return value of NaN. You can do
$("input[name=subs]").each(function(index) {
total = (parseInt($(this).val(), 10) || 0) + total;
$('#total').val(total);
});
Wich will always only add numbers to total.
Let's make that a possible answer, try using:
total = parseInt($(this).val()) + parseInt(total);
Also make sure $(this).val() has a proper value everywhere. If it's blank you will get NaN as a result. For almost any other you will get the right result: http://www.w3schools.com/jsref/jsref_parseInt.asp
It looks like you might be using the wrong selector to set the subtotal values you're using to do the final calculation. Shouldn't it be this:
$('input[id^=subtotal]').each(function(index){
$(this).val(subs_r[index]);
});