selectbox value calculation - php

I want to do a calculation between selectbox values. The problem with my code is that the first part of the calculation only gives me 0, which Motherboard valuequantity. the second part works fine which Chassisquantity. My formulas is motherbord*Quanity+chassis*quantity.
Here is my code:
function calculate() {
var parsedMotherboard = parseFloat(document.calcform.Motherboard.value || 0);
var parsedQuantity = parseFloat(document.calcform.Quantity.value || 0);
var parsedChassis = parseFloat(document.calcform.Chassis.value || 0);
var parsedQuantity1 = parseFloat(document.calcform.Quantity1.value || 0);
document.calcform.total.value = (parsedMotherboard * parsedQuantity + parsedChassis * parsedQuantity1);
}

It helps if you format your code more neatly:
function calculate() {
var parsedMotherboard = parseFloat(document.calcform.Motherboard.value || 0);
var parsedQuantity = parseFloat(document.calcform.Quantity.value || 0);
var parsedChassis = parseFloat(document.calcform.Chassis.value || 0);
var parsedQuantity1 = parseFloat(document.calcform.Quantity1.value || 0);
document.calcform.total.value = (parsedMotherboard * parsedQuantity +
parsedChassis * parsedQuantity1);
}
Have you checked that you are getting the correct values from the form? Make sure that the default option (I'm assuming the first one with a value of 0) has the selected attribute set so that one option is always selected.
Some other tips:
store a reference to the form, it's more efficient and makes for neater code
Since you set the value, you know it's formatted correctly so rather than using parseInt, just use the uary + operator to convert to number
Personal preference, but use shorter variable names so they're easier to work with
I don't understand the need for || 0. If the user doesn't select something, isn't the default value 0?
Here is an updated version:
function calculate() {
var form = document.calcform;
var mb = +form.Motherboard.value;
var mbQty = +form.Quantity.value;
var ch = form.Chassis.value;
var chQty = form.Quantity1.value;
form.total.value = mb*mbQty + ch*chQty;
}
Because each string value is involved in a multiplication, there is no need to explicitly convert to number, that will happen as a consequence of the multiplication, so you could write:
function calculate() {
var form = document.calcform;
form.total.value = form.Motherboard.value * form.Quantity.value +
form.Chassis.value * form.Quantity1.value;
}

do it with jQuery ...
$('#selectbox1').change(function() {
// do ajax if you want or store
var x = $('#selectbox1').attr('value'); // or you can use this.value
// and so on
});
and sum up the other selectboxes

Related

Sending and receiving multiple dates via AJAX to PHP

I hope I am able to explain what I'm trying to do properly, but I am trying to use AJAX to pass (using POST) quite a number of Dates to PHP file, to do checks if dates are valid (e.g. 31-FEB, 31-Apr).
I am not sure how many dates there will be, there are 12 entry boxes, maximum case 12 dates, minimum case 1. So the number of dates passed to the PHP file could be anything.
I want to be able to "roll" through (using numbers 0 1 2 like in an array) all the dates (and their D, M, Y) inside the PHP file, and also "roll" through dates passed back to the JS from PHP.
Jquery
var DAT = {}; //is such a declaration valid for an array?
k=0;
for(x=1;x<=12;x++)
{ I = "#ED" + x;
d= $(I).children('.dd').val();
m= $(I).children('.mmm').val();
y= $(I).children('.yyyy').val();
c= date_chk(d,m,y); //returns '1' if date ok
if(c==1) //Date OK
{ DATE[k] = [d,m,y];
alert(DATE[k][0]+" "+DATE[k][1]+" "+DATE[k][2]);
k++;
}
}
AJ.onreadystatechange = function(){
if((AJ.readyState == 4) && (AJ.status == 200))
{ var PH_RP = AJ.responseText;
alert("PHP REPLY:: " + PH_RP);
var DATE_Lst = JSON.parse(PH_RP);
alert("DATE1 Day::" + DATE_Lst.DT[0][0] + "DATE1 Month::" + DATE_Lst.DT[0][1] +"DATE1 Year::" + DATE_Lst.DT[0][2] );
alert("DATE2 Day::" + DATE_Lst.DT[1][0] + "DATE2 Month::" + DATE_Lst.DT[1][1] +"DATE2 Year::" + DATE_Lst.DT[1][2] );
}
var para = "DATESS=" + DATE; //? how do I send the whole stack of dates to the PHP file?
AJ.open("POST", "PHP/4_PHP_Check_Dates.php", true);
AJ.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
AJ.send(para);
Here is the PHP file::
$LOGARRY['DT'] = $_POST['DATESS'];
or
$LOGARRY['DT1'] = $_POST['DATESS'][1];
$LOGARRY['DT2'] = $_POST['DATESS'][2];
echo json_encode($LOGARRY);
Thanks.. any help appreciated
If you just want to check if a date is valid, you do not need the roundtrip to PHP, you can do that right in Javascript.
Detecting an "invalid date" Date instance in JavaScript
You asked how to send an array to PHP via XMLHttpRequest.
Since I avoid JQuery like the plague, I cannot really comment on your code, but here is a simple way to send X dates to you PHP script:
Three things:
it is simple (no errorchecking etc)
it used GET. Feel free to make it into a POST.
Open your javascript console to see the result.
<html>
<body>
<script>
// I assume you have an array with strings that might represent dates, like:
// dates[0] = "2022-10-09";
// dates[1] = "2021-13-09";
// ....
// dates[19] = "I am surely not a date";
// dates[20] = "2000-01-05";
var dates = [];
dates[0] = "2022-10-09";
dates[1] = "2021-13-09";
dates[2] = "I am surely not a date";
dates[3] = "2000-01-05";
var myTestDates = JSON.stringify(dates);
var myReq = new XMLHttpRequest();
myReq.addEventListener("load", reqListener);
var url = "dateChecker.php?dates=" + encodeURIComponent(myTestDates);
url += "&rand=" + Math.random();
myReq.open("GET", url , true);
myReq.send();
function reqListener () {
let passeddates = JSON.parse(this.responseText);
console.log(passeddates);
}
</script>
</body>
</html>
And the PHP script (named dateChecker.php):
<?php
$passedDates = json_decode( $_GET["dates"] );
$checkedDates = [];
foreach ($passedDates as $oneDate){
$d = DateTime::createFromFormat('Y-m-d', $oneDate);
$valid = ($d && $d->format('Y-m-d') === $oneDate) ? "valid" : "not valid";
$checkedDates[] = $oneDate . " is {$valid}";
}
echo json_encode($checkedDates);
?>

jquery addition in ajax result value not working

I want to add the result value plus already exists value in that textbox. but addition is not working concatenation is working
$.post('includes/ajax_timesheet.php', {
'action': 'add_kitamount',
'jobnumber': jobno,
'invoiceno': inv_no
}, function (data) {
var tot1 = $('#tot_dayrate').val();
var tot2 = $.trim(data);
var tot = tot1 + tot2;
alert(tot);
$("#tot_dayrate").val(tot);
});
Concatenation is happening because the values are being treated as string by + operator . Parse the values to number using any of the availaible javascript functions and then you will get correct total.
Ofcourse you need to handle for invalid inputs . Below is only showing an example for parse to number function.
var tot = parseInt(tot1) + parseInt(tot2);
Check here for string to number conversion and good explanation of difference between Number() and parseInt() , parseFloat() functions.
var tot = parseFloat(tot1) + parseFloat(tot2);
Convert to number
var tot = Number(tot1) + Number(tot2);
Or
var tot = parseInt(tot1) + tot2;
.val() returns the value of the element in String. You will first need to convert to to Number for performing arithmetic operations.
You can use Number() to convert the string into numbered format.
So your code would look something like this,
var tot1 = $('#tot_dayrate').val();
if(tot1!='') {
tot1=Number(tot1);
}
var tot2 = $.trim(data);
if(tot2!='') {
tot2=Number(tot2);
}
var tot = tot1 + tot2;
Make sure to check for blank value before converting String into int.

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.

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

Uncheck value for checkbox in jquery (with ajax and php)

I have an editable ajax table , and have a "unlock" field with a checkbox for every row.
When I check the chekbox I need to get the value 1 ( I'm ok for this part ! :)
My code to get the value of the cheked box:
( $("#unlock_input_" + ID).val(); ) )
But when I uncheck one of any checkbox , I need to get the value 0 ( I need help for this part)
So.... How can I do that in jquery ? Thx
You could throw on a :checked selector. Then you'll get back undefined when the box is unchecked, which is falsey, so:
var result = $("#unlock_input_" + ID + ":checked").val() || 0;
result will end up with the value of the checkbox if it's checked, or 0 if not, because of the way JavaScript's curiously-powerful || operator works.
Live example
Another way to write it:
var result = $("#unlock_input_" + ID).filter(":checked").val() || 0;
Or of course, the rather more direct:
var cb = $("#unlock_input_" + ID)[0],
result = cb.checked ? cb.value : 0;
change your code to this (using prop to ask for the checked-property):
var result = $("#unlock_input_" + ID).prop('checked')?1:0;
EDIT:
if you explicitly need the value instead of 1, just do:
var element = $("#unlock_input_" + ID);
var result = element.prop('checked')?element.val():0;
You can use the checked property of the checkbox to decide whether 1 or 0. Try this
if($("#unlock_input_" + ID)[0].checked){
alert("1");
}
else{
alert("0");
}
Alertnatively you can use jQuery is method to check whether the checkbox is checked or not.
if($("#unlock_input_" + ID).is(":checked")){
alert("1");
}
else{
alert("0");
}
You could check if it's chekced
if($("#unlock_input_" + ID).is(':checked')){
myVal = "1";
}
else{
myVal = "0";
}

Categories