jQuery live calc multirow input - php

This is my code:
<?php
for($i=1;$i<10;$i++){
echo '<input type="text" class="count value'. $i .'">';
echo '<input type="text" class="count '. $i .'value">';
echo '<input type="text" disabled="disabled" id="result'. $i .'"><p>';
}
echo '<input type="text" disabled="disabled" id="total"><p>';
?>
and jQuery:
$(document).ready(function(){
$(".count").keyup(function(){
for (var i = 0; i < 10; i++) {
var val1 = +$(".value"+ i).val();
var val2 = +$("."+ i +"value").val();
$("#result" + i).val(val1*val2);
}
});
});
$(document).ready(function(){
$(".count").keyup(function(){
for (var i = 0; i < 10; i++) {
var vala = 0;
vala += +$("#result"+ i).val();
}
$("#total").val(vala);
});
});
First part of code works great.
Return multiplication two inputs to id=result$i.
I have a problem with last one id=total.
It should return sum of all result X inputs
but now only return the last multiplication.
Do You have any idea what's wrong?

You can simplify your code by grouping the related input elements together in a containing div, using DOM traversal to retrieve the needed values, and joining the two for loops together. Try this:
<div class="group">
<input type="text" class="count valueA" />
<input type="text" class="count valueB" />
<input type="text" class="result" disabled="disabled" />
</div>
<!-- repeat the above as needed. Note that the incremental id is no longer needed -->
<p>
<input type="text" disabled="disabled" id="total" />
</p>
$(document).ready(function(){
$(".count").keyup(function() {
var total = 0;
$('.group').each(function() {
var $group = $(this);
var valA = +$group.find('.valueA').val() || 0;
var valB = +$group.find('.valueB').val() || 0;
var result = valA + valB;
total += result;
$group.find('.result').val(result);
});
$("#total").val(total);
});
});
Example fiddle

That is because you have defined variable vala to 0 in for loop. which should be outside for loop:
$(".count").keyup(function(){
var vala= 0;
for (var i = 0; i < 10; i++) {
vala += $("#result"+ i).val();
}
$("#total").val(vala);
});

Related

Get all input value in a array from a jquery dynamic table

I have created a dynamic table using jquery as follows:
$.ajax({
data : data,
type : "get",
url : url,
dataType : "json",
error : function(resp){
alert("Error !!");
},
success : function(resp){
table = '';
$.each(resp,function(indx,obj){
table += '<tr>';
table += '<td>'+parseInt(indx+1)+'</td>';
table += '<td>'+'<input type="text" value="'+obj.ServiceDetail.service_code+'">'+'</td>';
table += '<td>'+'<input type="text" value="'+obj.ServiceDetail.name+'">'+'</td>';
table += '<td>'+'<input type="text" value="'+obj.ServicePrice.discount_price+'">'+'</td>';
table += '</tr>';
});
$("tbody#sevice_table_body").append(table);
}
});
and a button :
<input type="button" class = "btn btn-success btn-sm" value="submit" >
now i want to get all input value in a array by click submit button so that can be inserted in a database table using jquery ajax.
You can use this code for cycling the input and add them to an array
var arrayOfVar = []
$.each($("input[type='text']"),function(indx,obj){
arrayOfVar.push($(obj).val());
});
You can use .serializeArray() it Encode elements as an array of names and values.
Find below fiddle for more info
$(function() {
var data = $("#tbl2 :input").serializeArray(); // For converting it to array
//If needed below code is converting it to object
var obj = {};
for (var i = 0, l = data.length; i < l; i++) {
obj[data[i].name] = data[i].value;
}
console.log(data); // Print Array in Console
console.log(obj);// Print Object in Console
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbl2">
<tr>
<td>
<input type="text" name="tb3" value="1" />
</td>
</tr>
<tr>
<td>
<input type="text" name="tb4" value="2" />
</td>
</tr>
<tr>
<td>
<input type="text" name="tb5" value="3" />
</td>
</tr>
<tr>
<td>
<input type="text" name="tb6" value="4" />
</td>
</tr>
</table>
Add attribute name with name and array .
$.ajax({
data : data,
type : "get",
url : url,
dataType : "json",
error : function(resp){
alert("Error !!");
},
success : function(resp){
table = '';
$.each(resp,function(indx,obj){
table += '<tr>';
table += '<td>'+parseInt(indx+1)+'</td>';
table += '<td>'+'<input type="text" name="service_code[]" value="'+obj.ServiceDetail.service_code+'">'+'</td>';
table += '<td>'+'<input type="text" name="name[]" value="'+obj.ServiceDetail.name+'">'+'</td>';
table += '<td>'+'<input type="text" name="discount_price[]" value="'+obj.ServicePrice.discount_price+'">'+'</td>';
table += '</tr>';
});
$("tbody#sevice_table_body").append(table);
}
});
Here you go with a solution
var inputData = [];
$('button[value="submit"]').click(function(){
$('input[type="text"]).each(function(){
inputData.push($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this will help you.
In your table section, add name attribute like this:
$.each(resp,function(indx,obj){
table += '<tr>';
table += '<td>'+parseInt(indx+1)+'</td>';
table += '<td>'+'<input name="services[' + indx + '][code]" type="text" value="'+obj.ServiceDetail.service_code+'">'+'</td>';
table += '<td>'+'<input name="services[' + indx + '][name]" type="text" value="'+obj.ServiceDetail.name+'">'+'</td>';
table += '<td>'+'<input name="services[' + indx + '][price]" type="text" name="service[' + indx + '][price]" value="'+obj.ServicePrice.discount_price+'">'+'</td>';
table += '</tr>';
});
This will produce names like services[0][code], services[0][name], etc.,
Now you can access the input values as an array in PHP:
$services = $_POST['services'];
foreach ($services as $index => $service) {
$code = $service['code'];
$name = $service['name'];
$price = $service['price'];
echo "$index : $code, $name, $price \n";
}

Multiply Checkbox Value with Input Box Value - Jquery

I am currently struggling to get the value I return from a checkbox to multiply with the value in the input box with jQuery.
I display a div when a checkbox is ticked to ask it for the quantity, thereafter I must multiply the quantity with the value of the checkbox.
Here is the current code:
$(document).ready(function () {
var sum = 0;
var qty = 0;
$("input[type=checkbox]").change(function () {
recalculateQty();
recalculateCheck();
if ($('#1').is(':checked')) {
$('#checked-1').show();
} else {
$('#checked-1').hide();
}
if ($('#2').is(':checked')) {
$('#checked-2').show();
} else {
$('#checked-2').hide();
}
if ($('#3').is(':checked')) {
$('#checked-3').show();
} else {
$('#checked-3').hide();
}
});
function recalculateQty() {
$('.qty').keyup(function () {
$('.qty').each(function () {
qty += parseInt(this.value, 10);
recalculateCheck();
});
});
}
function recalculateCheck() {
var sum = 0;
$("input[type=checkbox]:checked").each(function () {
sum += parseInt($(this).val());
});
$('.qty').keyup(function () {
$('.qty').each(function () {
qty += parseInt(this.value, 10);
});
});
$('#total').val(sum * qty);
}
});
<input type="checkbox" id="1" value="30" name="1" />
<input type="checkbox" id="2" value="60" name="2" />
<input type="checkbox" id="3" value="90" name="3" />
<div style="display:none;" id="checked-1">
<input type="text" name="product_1_qty" id="product_1_qty" placeholder="Quantity" class=" qty" value="0" />
</div>
http://jsfiddle.net/isherwood/9vRtJ/1/
You are trying to set an element value with total ID as a final result, but there is no such element in your html code. Just add this element in your html code (here i put another textbox):
<input type="text" id='total'>
Check out the Live demo for your fix
Or you can use better coding:(Read the comments) - Working DEMO
$(document).ready(function () {
var sum = 0;
var qty = 0;
$("input[type=checkbox]").change(function () {
if ($('#1').is(':checked')) {
$('#checked-1').show();
} else {
$('#checked-1').hide();
}
});
$('.qty').keyup(function () { // if user typed anyting in the Quantity
sum = parseInt($('#1').val()); // get checkbox value and change the data type to int
qty = parseInt($(this).val()); // get Quantity value and change the data type to int
//console.log(sum,qty);
if(sum && qty) { // if the values was not empty
$('#total').val(sum * qty); // show the result in the total element
} else { // if the values was empty
$('#total').val(''); // clear the result textbox
}
});
});

disabling/enabling the form values in php based on the if condition on the same page

here what i want to do is based on the if condition's value the total form should be disabled, how can i do that, here is the code i tried....
if ($today1 >= $saturday && $today1 <= $season1)
{
document.getElementById('season').disabled = false;
}
else if($today1 >= $startdate_offseasona1 && $today1 <= $enddate_offseasona1 )
{
document.getElementById('season').disabled = true;
}
else if($today1 >= $startdate_seasona2 && $today1 <= $season2)
{
document.getElementById(seasons).disabled = false;
}
and my form goes as follows:
<form action="" method="POST" id="season" name="season">
Min_Custom_League_size<input type="text" name="min_custom_league_size" size="40"/><br/>
Max_Custom_League_size:<input type="text" name="max_custom_league_size" size="40"/><br/>
Ranked_League_size:<input type="text" name="ranked_league_size" size="40"/><br/>
Screen_Capacity:<input type="text" name="screen_capacity" size="40"/><br/>
Wide_Release_Screens:<input type="text" name="wide_release_screens" size="40"/><br/>
Limited_Release_Screens:<input type="text" name="limited_release_screens" size="40"/><br/>
Starting_Auction_Budget:<input type="text" name="starting_auction_budget" size="40"/><br/>
Weekly_Auction_Allowance:<input type="text" name="weekly_auction_allowance" size="40"/><br/>
Minimum_Auction_Bid:<input type="text" name="minimum_auction_bid" size="40"/><br/>
<input type="submit" value="submit" name="submit" />
</form>
how can i do this based on the if condition value...what's wrong with my code??
You are mixing PHP (server-side) with JavaScript (client-side), and you can't do that. In any case, you have to disable the <input> elements, not the form itself.
Here is how to do that with PHP only:
<?php
$disableForm = $today1 >= $startdate_offseasona1 && $today1 <= $enddate_offseasona1;
?>
<form action="" method="POST" id="season" name="season">
Min_Custom_League_size<input type="text" <?php if($disableForm) echo 'disabled="disabled"'?> name="min_custom_league_size" size="40"/><br/>
<!-- repeat for all input elements -->
</form>
And here is a pure JavaScript way to disable the inputs unconditionally:
<script>
window.onload = function() {
var frm = document.getElementById('season');
var inputs = frm.getElementsByTagName('input');
for(var i=0; i<inputs.length; i++) {
inputs[i].disabled = true;
}
}
</script>
Note: you also have a typo inside your last else if block, it should be disabled, not diabled.
Use this for disable all elements in the form. likewise you can enable form elements
var theform = document.getElementById('seasons');
for (i = 0; i < theform.length; i++) {
var formElement = theform.elements[i];
if (true) {
formElement.disabled = true;
}
}

Adding multiple rows to database from dynamic field event

I have a dynamic event in JS in my form which adds another block of fields so my users can add another address:
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var $address = $('#address');
var num = $('.clonedAddress').length;
var newNum = new Number(num + 1);
var newElem = $address.clone().attr('id',
'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*11 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
if (newNum == 3) $('#btnAdd').attr('disabled', 'disabled');
});
$('#btnDel').click(function() {
$('.clonedAddress:last').remove();
$('#btnAdd').removeAttr('disabled');
if ($('.clonedAddress').length == 0) {
$('#btnDel').attr('disabled', 'disabled');
}
});
$('#btnDel').attr('disabled', 'disabled');
});
</script>
However, when I put my form action the page just refreshes when I click my 'add another address' button:
<form action="address.php" method="post" name="regForm" id="regForm" >
These are my fields:
if(empty($err)) {
for($i = 0; $i < 10; $i++)
{
$Street = $_POST['Street'][$i];
$Line2 = $_POST['Line2'][$i];
$Line3 = $_POST['Line3'][$i];
$Town = $_POST['Town'][$i];
$Postcode = $_POST['Postcode'][$i];
$Country = $_POST['Country'][$i];
$Tele = $_POST['Tele'][$i];
$Fax = $_POST['Fax'][$i];
$Type = $_POST['Type'][$i];
$Mobile = $_POST['Mobile'][$i];
$sql_insert = "INSERT into `address`
(`Street`,`Line2`,`Line3`,`Town`, `Postcode` ,`Country`,`Tele`,`Fax`,`Type`
,`Mobile` )
VALUES
('$Street','$Line2','$Line3','$Town','$Postcode','$Country',
'$Tele','$Fax','$Type', '$Mobile'
)";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
I want all addresses to go to mysql database.
I hope this is clear
Define buttons as followed: <input type="button" value="ButtonLabel" />.
My short test resulted in my <button> getting treated as submit type input by firefox. This means <button>FooBar</button> and <input type="submit" value="FooBar" /> are equivalent.
You might also want to simplify your javascript code. You can use the array notation for input names:
<input type="text" name="street[]" />
<input type="text" name="zip[]" />
<input type="text" name="street[]" />
<input type="text" name="zip[]" />
will result in $_POST["street"][0] and $_POST["street"][1] beeing filled with the user's input. This is what you want judging from your php code, anyway.
You don't need ids for all your input tags. Just keep one full set of inputs for one address and append this to your form. Maybe something like:
$('#address').append(
'<div>' +
'<input type="text" name="street[]" />' +
'<input type="text" name="zip[]" />' +
'</div>'
);
Or just have a full set hidden on your page and clone it, then append. I'm sure our jQuery pros will know a better solution.
And finally: Please sanatize your input with mysql_real_escape_string
$Street = mysql_real_escape_string($_POST['Street'][$i]);
// and so on for the other values.

Can validate an array of date[] but not process it?

I have a problem with this now, on the end of my mydate I have put [] so I can have an array to process and on the other page, I have process.php.
In the process.php, I have
foreach($_POST["mydate"] as $mydate ){
if($mydate != ''){
Date processed...etc etc....
}
If I put the [], it will store it but wont validate and if I dont put [], it will validate but not post?
Any thoughts?
<script type="text/javascript">
function checkdate(input){
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("/")[0]
var dayfield=input.value.split("/")[1]
var yearfield=input.value.split("/")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval=true
}
if (returnval==false) input.select()
return returnval
}
function CheckDates(inputs)
{
var i, len;
if (inputs.length) {
len = inputs.length;
for (i = 0; i < len; i++) {
if (!checkdate(inputs[i])) return false;
}
return true;
}
return checkdate(inputs);
}
function add(tbl1) {
var tbl = document.getElementById(tbl1);
var rowCount = tbl.rows.length;
var row = tbl.insertRow(rowCount);
var colCount = tbl.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newCell = row.insertCell(i);
newCell.innerHTML = tbl.rows[1].cells[i].innerHTML;
}
}
</script>
<form name "enter" action="enter.php" onSubmit="return Checkdate(this.mydate)" method="post">
<table id="day" border="1">
<tr><b>Valid date format:</b><br></tr>
<tr><td>
<input type="text" name="mydate" />
</table><br>
<input type="submit" value="submit" />
<input type="button" value="Add Row" onclick="add('day')"/>
</form>
EDITTED
removed the space but still doesnt work
If there are more than one of the input field, the name must be mydate[] so they are placed in an array, and in your processing code you have an extra space... $_POST['mydate '] won't work it must be $_POST['mydate']
edit: this line <input type="text" name="mydate" /> must be <input type="text" name="mydate[]" />
Try this construction:
foreach ($_POST["mydate"] as $mydate ) {
if(!empty($mydate) && !is_null($mydate)) {
}
}

Categories