2 name attributes for a field in a form - javascript

I have a script that calculates the values in each and shows the calulated values. At the end it also calculates the already calculated values from all div's
Here is the html code:
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
The problem is that I want to put all fields in a form and then submit them to a database.
However, all divs contain two input fields with name "r" and "p".
So, I am kind of stuck here because I cannot figure out how to make the names unique or how to have them passed to the DB using POST.
This is what the calculating script looks like:
<script type="text/javascript">//<![CDATA[
//any time the amount changes
$(document).ready(function() {
$('input[name=r],input[name=p]').change(function(e) {
var total = 0;
var $row = $(this).parent();
var rate = $row.find('input[name=r]').val();
var pack = $row.find('input[name=p]').val();
total = parseFloat(rate * pack);
//update the row total
$row.find('.amount').text(total);
var total_amount = 0;
$('.amount').each(function() {
//Get the value
var am= $(this).text();
console.log(am);
//if it's a number add it to the total
if (IsNumeric(am)) {
total_amount += parseFloat(am, 10);
}
});
$('.total_amount').text(total_amount);
});
});
//isNumeric function Stolen from:
//http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
//]]>
</script>

HTML:
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
PHP:
for ($i = 0; $i < count($_POST['p']); $i++) {
$rate = $_POST['r'][$i];
$pack = $_POST['p'][$i];
// do something with $rate and $pack
}
Since the browser submits all inputs (even if no value has been entered) and by specification it submits them in the order they are defined in the HTML code, you can rely that the elements in the two $_POST arrays will line up and the corresponding rate and pack will be received at the same index in the respective array.

Related

JS/jQuery: fire onchange from a disabled/readonly input without using button

The goal is to get the total Qty for the whole year.
The user will input numbers into 3 different textboxes(Jan,Feb,Mar), then the sum will be displayed into a disabled textbox(Quarter1).
Now I have 4 instances of these knowing we have 4 quarters/year.
I can easily display the sum per quarter, by using the onchange() function attached to the textboxes.
Now I am having issues getting the sum from the 4 disabled textboxes, knowing we can't use the onchange() on it because it's disabled.
I have searched and probably getting results only when a button is used.
TLDR: I am trying to display the sum from the four disabled textboxes to another textbox automatically, without the user clicking any button(just like firing the onchange event)
I have tried this one, wherein I tried to display the value of the first quarter to the total, and not working:
$(document).ready(function() {
$('input[id$=yearlyTotal]').bind("displaytotal", function() {});
$('#qtr1').change(function() {
var mos = document.getElementsByClassName("quantityA");
var mosCount = mos.length;
var total = 0;
for (var i = 0; i < mosCount; i++) {
total = total + parseInt(mos[i].value);
}
$('input[id$=yearlyTotal]').val(total).trigger('displaytotal');
});
});
Hope it's possible, thanks in advance
EDIT: Added UI
Showing Q1 (its just the same for the 4 qtrs)
<div class="form-group col-md-6">
<label class="col-sm-1 control-label">Jan:</label>
<div class="col-sm-2 small">
<input type="number" min="0" id="col3" class="form-control input-sm monthly" data-q="q1" name="January" />
</div>
<label class="col-sm-1 control-label">Feb:</label>
<div class="col-sm-2 small">
<input type="number" min="0" id="col4" class="form-control input-sm monthly" data-q="q1" name="February" />
</div>
<label class="col-sm-1 control-label">Mar:</label>
<div class="col-sm-2 small">
<input type="number" min="0" id="col5" class="form-control input-sm monthly" data-q="q1" name="March" />
</div>
<label class="col-sm-1 control-label">Q1:</label>
<div class="col-sm-2 small">
<input type="text" min="0" id="q1" class="form-control input-sm quarter" name="q1" style="background-color: #b3dcf5;" disabled />
</div>
</div>
This is the div for the total Qty
<div class="col-md-6">
<label class="col-sm-3 control-label" id="">Total Quantity:</label>
<div class="col-sm-3 small">
<input type="text" id="final" class="form-control input-sm" name="TotalQuantity" value="0" disabled />
</div>
</div>
Method 1:
Basically, what you need to do is to trigger the change event for the disabled quarter fields programatically, using jQuery .trigger() function.
As I don't know how your HTML is structured -this why it is always recommended to provide MCVE example- I made a demo example and I've done things differently, like below:
jsFiddle 1
var monthly = $('.monthly'),
Qrt = $('.quarter');
monthly.on('change, input', function() {
var $th = $(this),
// depending on the value of the data-q attribute, we pick
// all input fields with the same data-q as an array, then
//loop through them adding their values up
q = $th.attr('data-q'),
qArray = $th.parent().children('input[data-q="' + q + '"]'),
tempSum = 0;
for (var i = 0, ln = qArray.length; i < ln; i++) {
tempSum += +$(qArray[i]).val();
}
// we pick the corresponding quarter sum field, again depending
// on the value of the data-q attritues, and update its value, then
// we trigger the change event of this quarter sum field.
$('#' + q).val(tempSum).trigger('change'); // here you trigger it
});
Qrt.on('change', function() {
var qSum = 0;
for (var i = 0, ln = Qrt.length; i < ln; i++) {
qSum += +$(Qrt[i]).val();
}
$('#final').val(qSum);
});
.monthly { width: 32%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h3>Grand Total:</h3><input type="text" id="final" disabled><hr>
<h3>1st Q:</h3>
<input type="text" class="monthly" data-q="q1">
<input type="text" class="monthly" data-q="q1">
<input type="text" class="monthly" data-q="q1">
<br>Sum:<input id="q1" type="text" class="quarter" disabled>
<h3>2nd Q:</h3>
<input type="text" class="monthly" data-q="q2">
<input type="text" class="monthly" data-q="q2">
<input type="text" class="monthly" data-q="q2">
<br>Sum:<input id="q2" type="text" class="quarter" disabled>
<h3>3rd Q:</h3>
<input type="text" class="monthly" data-q="q3">
<input type="text" class="monthly" data-q="q3">
<input type="text" class="monthly" data-q="q3">
<br>Sum:<input id="q3" type="text" class="quarter" disabled>
<h3>4th Q:</h3>
<input type="text" class="monthly" data-q="q4">
<input type="text" class="monthly q-4th" data-q="q4">
<input type="text" class="monthly q-4th" data-q="q4">
<br>Sum:<input id="q4" type="text" class="quarter" disabled>
Method 2:
since any change you make to any .monthly field will change the corresponding value of quarter sum, and thus it'll also affect the value of the yearly sum, you don't need to capture the change event of the disabled quarter sum fields, just loop through their values and update the value of the yearly field, all should be done inside the on('change') event of the .monthly fields, like below:
jsFiddle 2
jQuery
var monthly = $('.monthly'),
Qrt = $('.quarter');
monthly.on('change, input', function() {
var $th = $(this),
q = $th.attr('data-q'),
qArray = $th.parent().children('input[data-q="' +q+ '"]'),
tempSum = 0,
qSum = 0;
for (var i = 0, ln = qArray.length; i < ln; i++) {
tempSum += +$(qArray[i]).val();
}
$('#' + q).val(tempSum);
// code below
for (var i = 0, ln = Qrt.length; i < ln; i++) {
qSum += +$(Qrt[i]).val();
}
$('#final').val(qSum);
});
Update:
For the updated HTML in the OP, replace qArray line with this one:
$th.parents('.form-group').find('input[data-q="' + q + '"]')`,
Note parents() is with "s" letter, unlike the former parent() which moves up a single level up the DOM, it does " search through the ancestors of these elements in the DOM tree and construct a new jQuery object from the matching elements ordered from immediate parent on up. ", so it travels up until we reach the matchng parent, here it is .form-group.
Then instead of children(), we use find().
jsFiddle 3
Please find the below code (Finding the total for quarter A & quarter B) for your reference. Please use same methodology for other quarters.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
/* FINDING THE QUARTER A AND QUARTER B */
function findingQuaterTotal () {
/* LOADING QUARTER A AND FINDING ITS TOTAL - STARTS */
var mosQuarterA = document.getElementsByClassName("quarterA"),
mosCountQuarterA = mosQuarterA.length,
totalQuarterA = 0,
i = 0;
for (i = 0; i < mosCountQuarterA; i++) {
totalQuarterA = totalQuarterA + parseInt(mosQuarterA[i].value);
}
/* ADDING INTO QUATER A DISABLED TEXTBOX */
$("#quarterA").val(totalQuarterA);
/* LOADING QUARTER A AND FINDING ITS TOTAL - ENDS */
/* LOADING QUARTER B AND FINDING ITS TOTAL - STARTS */
var mosQuarterB = document.getElementsByClassName("quarterB"),
mosCountQuarterB = mosQuarterB.length,
totalQuarterB = 0;
for (i = 0; i < mosCountQuarterB; i++) {
totalQuarterB = totalQuarterB + parseInt(mosQuarterB[i].value);
}
/* ADDING INTO QUARTER B DISABLED TEXTBOX */
$("#quarterB").val(totalQuarterB);
/* LOADING QUARTER B AND FINDING ITS TOTAL - ENDS */
/* TRIGGERING CHANGE EVENT IN THE DISABLED TEXTBOX WHOSE ID STARTS WITH QUARTER.*/
$("input[id^='quarter']").trigger("change");
};
/* ABOVE CHANGE TRIGGER WILL CALL BELOW EVENTS - STARTS */
$("input[id^='quarter']").change(function () { $("#final").val(parseInt($("#quarterA").val())+parseInt($("#quarterB").val()));
});
/* ABOVE CHANGE TRIGGER WILL CALL BELOW EVENTS - ENDS */
/* IF ANY VALUE CHANGES IN MONTH TEXT BOX, FLLWING FUNCTION WILL BE CALLED - STARTS */
$("input[id^='month']").on("change keyup",function () {
findingQuaterTotal();
});
findingQuaterTotal();
/* IF ANY VALUE CHANGES IN MONTH TEXT BOX, FLLWING FUNCTION WILL BE CALLED - ENDS */
});
</script>
</head>
<body>
<h2>Quater A</h2>
Jan - <input type="number" id="month1" value="6" class="quarterA"></br>
Feb - <input type="number" id="month2" value="16" class="quarterA"></br>
March - <input type="number" id="month3" value="25" class="quarterA"></br>
Quater A Total - <input type="number" id="quarterA" value="" disabled></br>
<br/><br/>
<h2>Quater B</h2>
April - <input type="number" id="month4" value="6" class="quarterB"></br>
May - <input type="number" id="month5" value="16" class="quarterB"></br>
June - <input type="number" id="month6" value="25" class="quarterB"></br>
Quater B Total - <input type="number" id="quarterB" value="" disabled></br>
Quarter A and Quarter B total - <input type="number" id="final" value="" disabled>
</body>
</html>

Javascript: How to check if each input value is duplicated to another input value

So i have a dynamic input field came from append with different class name and names, i want to check each of input field value already exist or duplicate.
This would look like
The first criteria_name is default and the others are appendend.
<input type="text" name="criteria_name" class="criteria_name">
<input type="text" name="criteria_name2" class="criteria_name2">
<input type="text" name="criteria_name3" class="criteria_name3">
<input type="text" name="criteria_name4" class="criteria_name4">
<input type="text" name="criteria_name5" class="criteria_name5">
I am trying to check each one of those if there is no duplicated else proceed.
var critname_arr = [];
var input_check;
var crit_name_of_first = $('input.criteriaNames').val();
var acappended = append_crit_header+1;
var count_to = 0;
for(var ab = 2; ab<=acappended; ab++){
var crit_arr;
if(crit_name_of_first == $('input.criteria_each_name'+ab+'').val()){
alert("Criteria cannot be duplicate");
return false;
}else{
input_check = $('input.criteria_each_name'+ab);
input_check.each(function(){
crit_arr = $.trim($(this).val());
});
critname_arr.push(crit_arr);
}
if($('input.criteria_each_name'+ab+'').val() == critname_arr[count_to]){
alert('criteria cannot be duplicate');
return false;
}
count_to++;
}
console.log(critname_arr);
Here is just an example of how you can do it. In the fiddle change one of the values to one that is already in another field (make a duplicate value) to see it do something. If there are no duplicates, it will not do anything. Click the "Button" text to run the duplicate check:
jsFiddle: https://jsfiddle.net/o52gjj0u/
<script>
$(document).ready(function(){
$('.ter').click(function(e) {
var stored = [];
var inputs = $('.criteria_name');
$.each(inputs,function(k,v){
var getVal = $(v).val();
if(stored.indexOf(getVal) != -1)
$(v).fadeOut();
else
stored.push($(v).val());
});
});
});
</script>
<!-- Just use an array name for the input name and same class name as well -->
<div class="ter">Button</div>
<input type="text" name="criteria_name[]" class="criteria_name" value="1" />
<input type="text" name="criteria_name[]" class="criteria_name" value="2" />
<input type="text" name="criteria_name[]" class="criteria_name" value="3" />
<input type="text" name="criteria_name[]" class="criteria_name" value="4" />
<input type="text" name="criteria_name[]" class="criteria_name" value="5" />

How do I use javascript or jquery to find a sum and product of values from a forms field inputs?

How do I use javascript or jquery to find a sum and product of number values that users enter into my forms fields. Thanks for your time and help.
Input 1 Value + Input 2 Value = Input A
Input A Value * .08 = Input B Value
Input A Value + Input B Value = Total Input
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>
WHAT IVE TRIED
<script>
var $form = $('#contactForm'),
$summands = $form.find('.sum1'),
$sumDisplay = $('#itmttl');
$form.delegate('.sum1', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
});
</script>
<script>
function multiply(one, two) {
if(one && two){
this.form.elements.tax.value = one * two;
} else {
this.style.color='blue';
}
}
</script>
Please find Fiddle link
JSFiddle
$(document).ready(function(){
$('#calculate').on('click',function(){
var v1 = $('#1').val(); // take first text box value
var v2 = $('#2').val(); // take second hidden text box value
$('#A').val(parseInt(v1)+parseInt(v2)); // set value of A
var aval = (parseInt($('#A').val()) * parseFloat(.8)); // calculate value of b
$('#B').val(aval);// set value of B
var totalval = parseInt($('#A').val()) + parseFloat(aval);
//calculate value for total
$("#total").val(totalval); // set total
})
});
I assume you want to update the fields when you lick the button? Created a snippet instead of a fiddle:
$("#button").click(function() {
$("#A").val( parseInt($("#1").val()) + parseInt($("#2").val()) );
$("#B").val(parseInt($("#A").val()) * .8);
$("#total").val( parseInt($("#A").val()) + parseInt($("#B").val()) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>

Update an input field when another input field is updated

I can't get this to work.
I got two forms, "mult" and "mult2" with a script making some simple calculations running through both. Both fields are dependent on data in another form called "recipe".
The thing is, i can actually get one of the forms to work doing it like i have done (see all my code under here) - the weird thing is that it's only mult2 that works and does all the calculations. Mult1 is not doing anything. The fields that needs to be updated in the end is "gravity" and "gravity2" - and only "gravity2" gets updated with the result of the calculation.
I know it's some long code bits here, but hope you can help me..
Here is the "recipe" form:
<form name="recipe">
<input type="text" size="1" maxlength="3" name="batchVal" value="30" onChange="calculate(malt1); calculate(malt2)"></td>
<input type="text" size="1" maxlength="3" name="efficiencyVal" value="75" onChange="calculate(malt1); calculate(malt2)"></td>
</form>
Here is the two forms, "mult" and "mult2" that both need the same datainputs from "recipe" form:
<form name="mult">
<select id="malt" name="malt" onChange="UpdateNextField(this,'ppg')">
<option>Choose fermentable..</option>
<?php
$query = $mysqli->prepare("SELECT id,maltname,maltebc,maltppg FROM malt WHERE mainid = ?");
$mainidcolumn = "1";
/* bind parameters */
$query->bind_param("i", $mainidcolumn);
$query->execute();
$menu_result = $query->get_result();
/* now you can fetch the results into an array */
while ($menu = $menu_result->fetch_assoc()) {
echo '<option value="'.$menu['maltppg'].'">' . $menu['maltname'] . ' ' . $menu['maltebc'] . ' EBC</option>';
}
echo '</select>';
?>
<input type="text" id="ebcfield" size="1" maxlength="3">
<input type="text" name="weightVal" size="1" maxlength="5" value="0" onChange="calculate(malt1)">
<input name="grainpercent" type="text" id="grainpercent" size="1" maxlength="2">
<input type="text" id="gravity" size="1" value="0" maxlength="4">
<input name="graincolor" type="text" id="graincolor" size="1" maxlength="3">
<input type="text" name="ppgVal" id="ppg" onMouseMove="calculate(malt1)">
</form>
<form name="mult2">
<select id="malt" name="malt" onChange="UpdateNextField(this,'ppg2')">
<option>Choose fermentable..</option>
<?php
$query = $mysqli->prepare("SELECT id,maltname,maltebc,maltppg FROM malt WHERE mainid = ?");
$mainidcolumn = "1";
/* bind parameters */
$query->bind_param("i", $mainidcolumn);
$query->execute();
$menu_result = $query->get_result();
/* now you can fetch the results into an array */
while ($menu = $menu_result->fetch_assoc()) {
echo '<option value="'.$menu['maltppg'].'">' . $menu['maltname'] . ' ' . $menu['maltebc'] . ' EBC</option>';
}
echo '</select>';
?>
<input type="text" id="ebcfield" size="1" maxlength="3">
<input type="text" name="weightVal2" size="1" maxlength="5" value="0" onChange="calculate(malt2)">
<input name="grainpercent" type="text" id="grainpercent" size="1" maxlength="2">
<input type="text" id="gravity2" size="1" value="0" maxlength="4">
<input name="graincolor" type="text" id="graincolor" size="1" maxlength="3">
<input type="text" name="ppgVal2" id="ppg2" onMouseMove="calculate(malt2)">
</form>
And finally the javascript that does the calculations based on data in the input fields. Calculate(malt1) and Calculate(malt2) does the same thing, it's just two instances of the same calculation.
<script type = "text/javascript">
function UpdateNextField(which,ppg) {
document.getElementById(ppg).value = which.value;
}
function UpdateNextField(which,ppg2) {
document.getElementById(ppg2).value = which.value;
}
</script>
<!-- calculations for malt 1-5 -->
<!-- form 1 - fermentable 1 -->
<script type="text/javascript">
function calculate(malt1){
var weightVal = document.mult.weightVal.value;
var ppgVal = document.mult.ppgVal.value;
var batchVal = document.recipe.batchVal.value;
var efficiencyVal = document.recipe.efficiencyVal.value;
var showValue = 0;
var showValue = ((weightVal * ppgVal * 0.000008345) * (efficiencyVal) * 10) / batchVal + (1000);
showValue = Math.round(showValue * 1) / 1;
if (!isNaN(showValue)) {
document.getElementById('gravity').value = showValue;
}
}
function calculate(malt2){
var weightVal2 = document.mult2.weightVal2.value;
var ppgVal2 = document.mult2.ppgVal2.value;
var batchVal = document.recipe.batchVal.value;
var efficiencyVal = document.recipe.efficiencyVal.value;
var showValue2 = 0;
var showValue2 = ((weightVal2 * ppgVal2 * 0.000008345) * (efficiencyVal) * 10) / batchVal + (1000);
showValue2 = Math.round(showValue2 * 1) / 1;
if (!isNaN(showValue2)) {
document.getElementById('gravity2').value = showValue2;
}
}
</script>
You have a few problems with your function names and duplicate IDs, as noted by Jay and LcLk. But, assuming you fix these, you can save a lot of time and grief by using jQuery. For example:
HTML
<input type="text" id="first" />
<input type="text" id="second" />
Javascript
$("#first").keypress(function(){
/* your custom code goes here */
console.log("A key was pressed.");
});
What this says is that anytime a key is pressed while the first input is selected, it will print out A key was pressed in the console. You can then either directly call your calculation functions from within that anonymous inner function, or pass them directly into keypress();.

auto calculate without clicking any button

Hi I'm new for programming and I'm facing one problem.
I have 3 input for values and 1 input for total. What I need is when I change the value in any input total should change automatically.
<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />
And for total I have:
<input type="text" class="form-control" name="total" id="total" value="" />
And below is the script:
<script type="text/javascript">
$('#amount').change(function() {
$('#total').attr('value', function() {
var result = 0;
$('#amount').each(function() {
result += $(this).attr('value');
});
return result;
});
});
</script>
You have multiple ids for amount. These should be changed to classes. In addition, the value for each amount will be picked out by jQuery as a string, so that needs to be changed to an integer:
$('.amount').change(function () {
var result = 0;
$('.amount').each(function () {
result += +$(this).val();
});
$('#total').val(result);
});
Fiddle.

Categories

Resources