several select dropdown boxes to add values - php

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

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.

PHP/MySQL Form Values SUM with dropdown options

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

Dynamically Created Checkbox calculation, Not showing properly

I have a javascript function that create Checkbox by drop_down's selection. When I clicked the add button , system will create checkbox(es) with values.
function addElement()
{
var e= document.getElementById('top-addon');
var tops = e.options[e.selectedIndex].text;
var tops_value=e.options[e.selectedIndex].value;
// alert(tops_value);
var ni = document.getElementById('myDiv');
num += 1;
//var newdiv = document.createElement('div');
var countedName = num;
// newdiv.setAttribute('id',Name);
var x = document.createElement("input");
x.type = "checkbox";
x.name = "toppings[]";
x.setAttribute('id',countedName);
x.checked = true;
x.value = tops_value;
//var inner_text = tops + '<a href=\'#\' onclick=\'removeElement('+countedName+')\'> [x] </a>';
//var text= document.createTextNode(inner_text);
x.innerHTML=tops;
ni.appendChild(x);
//ni.appendChild(inner_text);
}
I had make some screenshots to explain you my current problems. Please check my screenshot for more clear picture.
This is like this, for an item like ice-cream, customers can add many toppings example , nuts, jelly etc.
Then I have another problem.Created checkbox's are not shown . I can only see square box(es)
Please see my second attached picture below.Seems okay to me.But I can't see any description text(s).
What I am trying to achieve is
to show selection
Calculate the items,they will be generated with checked value. I have already achieve the code to remove the generated toppings. So I want to calculate the total value of generated items and they should be changeable.
Example. if remove a generated item. Total toppings should decrease.Thanks for your help in advance.
For your first problem: In order to display text for a checkbox, you should put checkbox inside label. Here is modified code for you
function addElement()
{
var e= document.getElementById('top-addon');
var tops = e.options[e.selectedIndex].text;
var tops_value=e.options[e.selectedIndex].value;
// alert(tops_value);
var ni = document.getElementById('myDiv');
num += 1;
//var newdiv = document.createElement('div');
var countedName = num;
// newdiv.setAttribute('id',Name);
var x = document.createElement("input");
x.type = "checkbox";
x.name = "toppings[]";
x.setAttribute('id',countedName);
x.checked = true;
x.value = tops_value;
//x.innerHTML=tops; We don't need to set text to checkbox.
/* These lines are added */
var label = document.createElement("label");
label.appendChild(x);
var span = document.createElement("span");
span.innerText = tops;
label.appendChild(span);
/* End of added lines */
// Beware that we are adding label to div, instead of checkbox.
ni.appendChild(label);
}
For your second problem: To calculate grand total of cart, you need to define a function (let's say calculateTotal) that implements sort of this pseudocode:
function calculateTotal
begin
get all checkboxes under myDiv
for each selected check box
begin
get check box id
get substring of id, after comma (",")
add substring (price) to total
end
end
This method should be triggered whenever user clicks add item button, remove item button, and checkboxs' onChange events fire.
I guess this answer should address your issue with checkboxes text: https://stackoverflow.com/a/10143276/1492792

jQuery new option needs sorting

I've got two dropdowns, as a result of changing the first one it triggers a jquery change() that does a post with the company id from the first dropdown. That then runs a sql query to get a list of people that work for that company and fills the select box with options. This is working fine and I've got the sql query set to ORDER BY admin_name. But when jquery starts inserting the options into the dropdown it appears to be sorting by the option value instead (admin_id). What can I do to keep the options ordered by the admin_name (the text of the option). Below is the jQuery code responsible for adding the options:
$.post("listSignedBy.php", { company_id: company_id },
function(data) {
alert(data); <-- this shows that the data is sorted correctly by the admin name.
var select = $('#signed_by');
if(select.prop) {
var options = select.prop('options');
}
else {
var options = select.attr('options');
}
$('option', select).remove();
var obj = jQuery.parseJSON(data);
options[options.length] = new Option('-- Select Signed By --', '');
$.each(obj, function(val, text) {
options[options.length] = new Option(text, val);
});
select.val(selectedOption);
});
Thank you for any assistance and please let me know if you need any further information to help troubleshoot/fix.
As requested, example JSON data:
{"19082":"Aaron Smith","19081":"Becky Doe"}
So in this case what I WANT is:
<option value='19082'>Aaron Smith</option>
<option value='19081'>Becky Doe</option>
But instead of sorting by the text, it's sorting by the value so I get:
<option value='19081'>Becky Doe</option>
<option value='19082'>Aaron Smith</option>
The object is not sorted.. It is actually getting inserted in the order how it is iterated.
However, in case if the order of returned response is not in the desired order then the best way is it insert the options first and sort the options. See below,
DEMO: http://jsfiddle.net/gGd82/3/
// convert OPTIONs NodeList to an Array
// - keep in mind that we're using the original OPTION objects
var ary = (function(nl) {
var a = [];
for (var i = 0, len = nl.length; i < len; i++) {
a.push(nl.item(i));
}
return a;
})(options);
// sort OPTIONs Array
ary.sort(function(a, b) {
return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
});
// remove all OPTIONs from SELECT (don't worry, the original
// OPTION objects are still referenced in "ary") ;-)
options.length = 0;
// (re)add re-ordered OPTIONs to SELECT
select.html(ary);
select.prepend($('<option />').text('-- Select Signed By --').val(''));
References: Sorting dropdown list using Javascript
I was able to get it working by creating the following function and then referencing that function just after the .each() that entered all of the options in:
function Sort(a, b) {
return (a.innerHTML > b.innerHTML) ? 1 : -1;
};
$.post("listSignedBy.php", { company_id: company_id },
function(data) {
var select = $('#signed_by');
if(select.prop) {
var options = select.prop('options');
}
else {
var options = select.attr('options');
}
$('option', select).remove();
var obj = jQuery.parseJSON(data);
options[options.length] = new Option('-- Select Signed By --', '');
$.each(obj, function(val, text) {
options[options.length] = new Option(text, val);
});
$('#signed_by option').sort(Sort).appendTo('#signed_by');
select.val(selectedOption);
});

Categories