PHP/MySQL Form Values SUM with dropdown options - php

I need some guidance and excuse me that I'm not posting any samples of what I have but right now I'm blocked.
I have a database table with the following values to load the form values from.
COLUMNS
q_answer | ans_value
Yes | 20
No | 0
Now what I'm trying to accomplish is to create a form with 6 questions and next to each question a dropdown with the values Yes and No and below it a box that displays the value of the answer, meaning YES = 20 , NO = 0
After all the questions are answered, I need it to sum the value and echo it on a "Final Score" field but there is a condition. If the 6th question is answered "Yes", then the final score value should be 0, otherwise if the answer is NO, then the final score should be the sum of the value of the first 5 question.
I need the resulting value of each question to be stored in another DB table (form_results) with the columns, q1_score, q2_score, q3_score, q4_score, q5_score, q6_answer, final_score
I tried to do this using PHPRunner but have been unsuccessful which is why I'm not posting the code for the form I've been trying to use but any assistance with this, I can use it to implement it into my project.
Thank you,
UPDATE:
I been playing around with javascript to try and accomplish what I want and it's not the cleanest code but it's partially doing the trick. I just can't get to SUM the values if the 6th question is NO. all it does is to COUNT how many answered there are but not the actual SUM of the resulting values of each question and on top of that, it erased the resulting values when I choose "No" in the 6th question.
var ctrlquestion_1 = Runner.getControl(pageid, 'question_1');
var ctrlquestion_2 = Runner.getControl(pageid, 'question_2');
var ctrlquestion_3 = Runner.getControl(pageid, 'question_3');
var ctrlquestion_4 = Runner.getControl(pageid, 'question_4');
var ctrlquestion_5 = Runner.getControl(pageid, 'question_5');
var ctrlquestion_6 = Runner.getControl(pageid, 'question_6');
var ctrlq1_score = Runner.getControl(pageid, 'q1_score');
var ctrlq2_score = Runner.getControl(pageid, 'q2_score');
var ctrlq3_score = Runner.getControl(pageid, 'q3_score');
var ctrlq4_score = Runner.getControl(pageid, 'q4_score');
var ctrlq5_score = Runner.getControl(pageid, 'q5_score');
var ctrlfinal_score = Runner.getControl(pageid, 'final_score');
ctrlquestion_1.on('change', function(e){
if (this.getValue() == 'Yes'){
ctrlq1_score.setValue(20);
}else{
ctrlq1_score.setValue(0);
}
});
ctrlquestion_2.on('change', function(e){
if (this.getValue() == 'Yes'){
ctrlq2_score.setValue(20);
}else{
ctrlq2_score.setValue(0);
}
});
ctrlquestion_3.on('change', function(e){
if (this.getValue() == 'Yes'){
ctrlq3_score.setValue(20);
}else{
ctrlq3_score.setValue(0);
}
});
ctrlquestion_4.on('change', function(e){
if (this.getValue() == 'Yes'){
ctrlq4_score.setValue(20);
}else{
ctrlq4_score.setValue(0);
}
});
ctrlquestion_5.on('change', function(e){
if (this.getValue() == 'Yes'){
ctrlq5_score.setValue(20);
}else{
ctrlq5_score.setValue(0);
}
});
ctrlquestion_6.on('change', function(e){
if (this.getValue() == 'Yes'){
ctrlfinal_score.setValue(0);
}else{
ctrlfinal_score.setValue(ctrlq1_score.setValue() + ctrlq2_score.setValue() + ctrlq3_score.setValue() + ctrlq4_score.setValue()+ ctrlq5_score.setValue());
}
});

Related

How to SUM each column in this dynamically created table like excel

I'll try my best to explain my current problem.
I've created a view, something like excel. It's dynamically created. (see below)
A B C
| 1| | 3| | 7| // The input format is `<input type='text' class='inputitem' id='colA_row1' />`
| 2| | 6| | 8| // The `id` of this `inputitem`is defined by the number of columns and rows automatically
| 9| | 7| | 4|
|12| |16| |19| // The format of total textbox is `<input type='text' class='totalitem' id='total_colA' />
//// The `id` of this `totalitem` is defined by the number of column automatically
User may input any number to any inputitem and the value of totalitem is adjusted to the SUM of value in each column. (in example, if user change the value of column A row 2 to 9, the totalcolumn of column A is changed into 19)
This is my current jquery code:
$('.inputitem').on('keyup', function(){
var _inputitem = $(this);
var _inputitem_arr = $(this).attr('id').split('_');
var _inputitem_col = _inputitem_arr[0];
var _inputitem_row = _inputitem_arr[1];
/*SUM SCRIPT*/
var sum_item = 0;
$('.inputitem').each(function(i){
var inputitem_val = parseFloat($(this).val().replace(',', ''));
$('.totalitem').each(function(i){
var _totalitem = $(this);
var _totalitem_arr = $(this).attr('id').split('_');
var _totalitem_col = _totalitem_arr[1];
if(_inputitem_col == _totalitem_col){
sum_item = sum_item + inputitem_val;
_totalitem.val(sum_item);
}
});
});
/*END SUM SCRIPT*/
});
My current script give wrong value of total item. It seems to adding the SUM of different column into the formula. Any help and suggestion is much appreciated
Think about the flow of this code.
Your outermost function executes when the user finishes a key press (keyup event) on any input element on your page that has class "input item". So far, so good.
You initialize the sum to 0 and then you call
$('.inputitem').each(function(i){
This call means that for every element on the page that has class "input item", you will run the entire script inside the inner function. So for the first inputitem (perhaps the one in the top left, perhaps not) we get the value 1.0 in inputitem_val.
Here's where the trouble really starts. Next you call the each function for all of your total cells. But this is a nested call. So you are doing that inner-most function anew for each of the 9 (or however many) cells of your outer each loop. Here's a fix un-nests the functions:
$('.inputitem').on('keyup', function(){
var _inputitem = $(this);
var _inputitem_arr = $(this).attr('id').split('_');
var _inputitem_col = _inputitem_arr[0];
//whichever column this cell is in is the column we need to re-sum
var active_col = _inputitem_col
/*SUM SCRIPT*/
var sum_item = 0;
//iterate through each input cell
$('.inputitem').each(function(i){
var _inputitem = $(this);
var _inputitem_arr = $(this).attr('id').split('_');
var _inputitem_col = _inputitem_arr[0];
//check whether the current input cell is in the active column
if(_inputitem_col == active_col){
//if so, add it to our partial sum
var inputitem_val = parseFloat($(this).val().replace(',', ''));
sum_item += inputitem_val;
}
});
//find and update only the relavent sum cell
$('.totalitem').each(function(i){
var _totalitem = $(this);
var _totalitem_arr = $(this).attr('id').split('_');
var _totalitem_col = _totalitem_arr[1];
if(_inputitem_col == _totalitem_col){
_totalitem.val(sum_item);
}
});
/*END SUM SCRIPT*/
});
$('.inputitem').on('keyup', function(){
var _inputitem_arr = $(this).attr('id').split('_');
var _inputitem_col = _inputitem_arr[0];
var $totlaSelector = '#total_' + _inputitem_col;
var $ColTotal = 0;
$('[id^="'+_inputitem_col+'"]').each(function(i){
var $thisVal = 0;
if($(this).val() != ''){
$thisVal = parseInt($(this).val());
}
$ColTotal = $ColTotal + $thisVal;
});
$($totlaSelector).val($ColTotal);
});
I have updated your jQuery on keyup event.

Fixing jQuery plugin to handle duplicating nested fields with unique ID's

I have a quick question for you guys here. I was handed a set of lead generation pages and asked to get them up and running. The forms are great, expect for one small issue... they use the jQuery below to allow users to submit multiple instances of a data set by clicking an "Add another item" button. The problem is that the duplicated items are duplicated EXACTLY. Same name, id, etc. Obviously, this doesn't work when attempting to process the data via PHP, as only the first set is used.
I'm still learning jQuery, so I was hoping that someone could point me in the right direction for how to modify the plugin below to assign each duplicated field an incremental integer on the end of the ID and name assigned. So, the fields in each dataset are Role, Description, Age. Each additional dataset will use the ID & name syntax of fieldname#, where # represents numbers increasing by 1.
Thanks in advance for any advice!
/** https://github.com/ReallyGood/jQuery.duplicate */
$.duplicate = function(){
var body = $('body');
body.off('duplicate');
var templates = {};
var settings = {};
var init = function(){
$('[data-duplicate]').each(function(){
var name = $(this).data('duplicate');
var template = $('<div>').html( $(this).clone(true) ).html();
var options = {};
var min = +$(this).data('duplicate-min');
options.minimum = isNaN(min) ? 1 : min;
options.maximum = +$(this).data('duplicate-max') || Infinity;
options.parent = $(this).parent();
settings[name] = options;
templates[name] = template;
});
body.on('click.duplicate', '[data-duplicate-add]', add);
body.on('click.duplicate', '[data-duplicate-remove]', remove);
};
function add(){
var targetName = $(this).data('duplicate-add');
var selector = $('[data-duplicate=' + targetName + ']');
var target = $(selector).last();
if(!target.length) target = $(settings[targetName].parent);
var newElement = $(templates[targetName]).clone(true);
if($(selector).length >= settings[targetName].maximum) {
$(this).trigger('duplicate.error');
return;
}
target.after(newElement);
$(this).trigger('duplicate.add');
}
function remove(){
var targetName = $(this).data('duplicate-remove');
var selector = '[data-duplicate=' + targetName + ']';
var target = $(this).closest(selector);
if(!target.length) target = $(this).siblings(selector).eq(0);
if(!target.length) target = $(selector).last();
if($(selector).length <= settings[targetName].minimum) {
$(this).trigger('duplicate.error');
return;
}
target.remove();
$(this).trigger('duplicate.remove');
}
$(init);
};
$.duplicate();
Add [] to the end of the NAME attribute of the input field so for example:
<input type ="text" name="name[]"
This way your $POST['name'] will hold an array of strings. For that element. It will be an array with keys that are numbers from 0 to however many items it holds.

clone span into textfield from sum of fields

How do I take the result from "#sum" and have it auto duplicated in a textfield so that when I submit a form, the value gets sent also?
<script>
$(document).ready(function() {
$(":text").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum=0;
$(":text").each(function() {
if(!isNaN(this.value) && this.value.length!=0 {
sum+=parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(0));
$("#myTextField").val(sum.toFixed(0)); //adding to text field
}
</script>
Is there a quick fix to this?
This is where the actual value updates on the HTML page.
<span id="sum">0</span>
It is not adding right. If I type in 500 in one of the fields it now takes the first number and repeats, so if I type 500 it outputs as 555
any help?
Your issue is is that ":text" is selecting myTextField. So your final value is being added back in.
5 = 5; 50 + 5 = 55; 500 + 55 = 555; You can try using the not selector.
$(":text:not('#myTextField')")
http://jsfiddle.net/RhRbR/
$(":text:not(#myTextField)").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
sum+=parseFloat(this.value);
}
})
The fiddle can show you the way.

several select dropdown boxes to add values

How can I find the values of two different select dropdowns and add the two values together upon selection(not submition) if they have the same "name" and then place the sum value into an array using jquery?
EDIT
For a little clarification, I am dynamically creating the list which needs to look like this
BOX A, BOX A, TITLE
BOX B, BOX B, TITLE
BOX C, BOX C, TITLE
etc...
Every list will be different and rarely the same. Next time the boxes could be D E or F. When selected(currently .onchange) All corresponding boxes need to be added together then pushed into a seperate array if the value is not empty...
var s=[sumOfAs, sumOfBs, sumOfCs];
I hope this helps...
Also the back end is PHP
THANKS!
EDIT
Here is the jquery code that pushes the first set of values into an array...
$("#selectionBox select").change(function(){
s = [];
$("#selectionBox select option:selected").each(function(){
$("#selected_songs").text('');
var v = $(this).val();
if(v != ''){
s.push(v);
}
if(s != ""){
$('#selectionButton').show();
var mw = $("#list_month_New").val();
var dw = $("#list_day_New").val();
var yw = $("#list_year_New").val();
var t = $("#listTitle").val();
if(mw == "" || dw == "" || yw == ""){
$("#songListWarning").show();
}else{
$("#songListWarning").hide();
}
}else{
$("#list_month_New").val();
$("#list_day_New").val();
$("#list_year_New").val();
$("#listTitle").val();
$('#selectionButton').hide();
}
});
s.sort();
jQuery.each(s, function(){
O = "";
O = this+"<br />";
str = /&(.+)/.exec(O)[1];
num = O.replace(/\-.*/, '');
fullString = '<span style="color:black">'+num+'</span> - '+str;
$("#selected_songs").append(fullString);
});
I just need to figure out how to add another value to the initial value?
var runningTotals = {};
$('select').each(function() {
var $this = $(this);
var name = $this.attr("name");
var val = runningTotals[name];
if (!val) {
val = 0;
}
val += +($this.val());
runningTotals[name] = val;
});
Please refer to this fiddle
EDIT
Edited to update for the change edit you made

jQuery - saving/using cookies

I am currently developing a shopping cart solution and I have a field, which is used for tax.
What I'm looking to do, is when the user selects the checkbox field for tax, then this is stored in the cookie, so when they go to other pages and then return to the cart, then these fields are checked.
I am using http://plugins.jquery.com/project/Cookie to achieve this.
I can create the cookie for the checkboxes, but I am struggling to then check the cookie and if it was for a checkbox, then set the checkbox as 'checked'.
I also need, the deletion of cookies. When the user unchecks the box, to the call something like $.cookie("vat_1", null)
I have the following code so far:
$(document).ready( function() {
$('input:checkbox[name="<?php echo $prod; ?>"]').click(function() {
var name = $(this).attr("name");
var value = $(this).val();
var date = new Date();
date.setTime(date.getTime() + (30 * 60 * 1000));
$.cookie(name, value, { expires: date });//Set the expires time as per your requirement.
cookie = $.cookie(name);
alert(cookie);
})
});
All help is muchly appreciated.
Thanks
To support loading the previously checked boxes, at the top of the document.ready() function, insert the following code:
$('input:checkbox').each(function(index) {
cookie = $.cookie($(this).attr("name"));
if (cookie == 1) {
$(this).prop('checked', true);
});
This should loop through each checkbox on the page, lookup the relevant cookie, and alter the checkbox accordingly.
In terms of deleting the cookies and setting them correctly in the first place, you should not be using the val() of the checkbox. Instead you should be looking up its checked property:
$('input:checkbox[name="<?php echo $prod; ?>"]').click(function() {
var name = $(this).attr("name");
var value = $(this).prop('checked');
var date = new Date();
date.setTime(date.getTime() + (30 * 60 * 1000));
if (value) {
$.cookie(name, 1, { expires: date });
} else {
$.cookie(name, null);
}
cookie = $.cookie(name);
alert(cookie);
})
These two pieces of code should be combined as such
$(document).ready( function() {
//first code above
//second code above
});

Categories