i am working in a code igniter. i have a form which contain three input boxes in a row . ..i put them in a for loop which is less then five ..so now my form has five rows with three input boxes in a row .. now what i am doing write now i am adding the values of two input boxes and displaying in 3rd input box .. now what i want to do is when every "total"(3rd input box) is filled .. then i am gonna add all the totals and then display all the totals in last box which i display at the bottom ..
here is my view
<td><input type="text" id = "price_<?php echo $i ?>"
onkeyup='addition(<?php echo "$i"?>)'>
</td>
<td> <input type="text" id = "quantity_<?php echo $i ?>" onkeyup='addition(<?php echo "$i"?>)'>
</td>
<td><input type="text" id = "total_<?php echo $i ?>">
</td>
<?php echo form_input($subtotal)?></td> // here i want to display sum of all the totals
here is my javascript..this function is multiplying the price and quantity ..i mean first and 2nd input box and then displaying in the 3rd box ..
function addition (obj)
{
var subtotal = 0;
var num1=parseInt($('#price_'+obj).val());
var num2=parseInt($('#quantity_'+obj).val());
var num4=parseInt($('#total_'+obj).val());
if ($('#price_'+obj).val() !='' && $('#quantity_'+obj).val() !='')
{
var num3=num1*num2;
$('#total_'+obj).val(num3);
}
else
{
$('#total_'+obj).val('');
}
}
i have uploaded the image also ..
I see that you use jQuery, I have modified your code a bit to use jQuery better. You can see the demo at JsBIN
The idea is lock all "total" cell, when you update one "total" cell by calculating the result. Sum all "total" cell to the "grand-total" cell. I listen on the "keyup" event.
Here is jsFiddle example: http://jsfiddle.net/Ner7M/2/
Code of interest:
var table = $('table');
// nth-child is 1-based, not 0
function totalColumn(table, idx) {
var total = 0;
var tds = $('table')
.find('tr td:nth-child(' + idx + ') input')
.each(function() {
total += parseInt($(this).val());
});
return total;
}
totalColumn(table, 3);
Related
I have here shopping cart using php. I add a script for getting the sum of all input fields. What I need to do is get the sum of all quarter per row. The problem is all of total fields gets the sum value of row. How I can get the sum per row?
<script type="text/javascript">
$('.qtys').blur(function() {
var sum = 0;
$('.qtys').each(function() {
sum += Number($(this).val());
});
$('.qty_total').val(sum);
});
</script>
while($obj = $results->fetch_object())
{
<td><input type="text" name="product_qty" size="1" class="qty_total"/></td>
<td><input type="text" name="qty1st" size="1" class="qtys"/></td>
<td><input type="text" name="qty2nd" size="1" class="qtys"/></td>
<td><input type="text" name="qty3rd" size="1" class="qtys"/></td>
<td><input type="text" name="qty4th" size="1" class="qtys"/></td>
}
The selector $('.qty_total') will give you call the elements having class qty_total but you need only one in the current row. Use the qty_total in the current row. You can get the parent row but $(this).closest('tr') then you can find the the qty_total using find()
Also use $(this).closest('tr').find('.qtys').each instead of $('.qtys').each(function()
Live Demo
Your code
<script type="text/javascript">
$('.qtys').blur(function () {
var sum = 0;
$(this).closest('tr').find('.qtys').each(function () {
sum += Number($(this).val());
});
$(this).closest('tr').find('.qty_total').val(sum);
});
</script>
Check this Demo Fiddle
<script type="text/javascript">
$('.qtys').blur(function() {
var sum = 0;
$(this).closest('tr').find('.qtys').each(function() { //.qtys of current row,
sum += Number($(this).val());
});
$(this).closest('tr').find('.qty_total').val(sum); // total of current row
});
</script>
You need Quarter values of current row. $(this).closest('tr') gives you the <tr> parent of current <td>. So, the selector would update values of current row instead of all the rows which your previous code did.
All your operations need to work on current row being manipulated. .closest('tr') helps in manipulating only the child elements of current row.
Alternative : $(this).parents('tr')
this is the way to do it:
//gets the inputs in the correct row
$(this).parent('tr').children('.qtys').each(function(){
//sums it
totalSum=totalSum+$(this).val();
//puts it in the total input
$(this).parent('tr').children('td:nth-child(3)').children('input').val(totalSum);
});
I have a table with a button that adds 5 rows with cells to the table when clicked. I want to bind an event to cells in the 5th column of the table. All of these cells are named "Count_" followed by the row number. So, the cell in Row 0 is:
<td name="CountCell_0">
<input type="text" name="Count_0">
</td>
And I'm trying to update the input with name Count_X (where X is the row number).
The binding works for the cells that existed on the page originally. However, the event is not triggering for cells that were added with the button.
Here is an example of a cell that was dynamically added:
<td>
<input type="text" name="Count_348">
</td>
Here is my Jquery event:
$(document).ready(
function() {
$(document).on('change','[name^="Count_"]',function() {
console.log('here'); //not triggering on dynamic cell
var cell = $(this).attr('name');
var idx = cell.split('_')[1];
var amount = $(this).val() * $('[name="AvgCost_' + idx + '"]').html();
$('#ExtendedCostCell_' + idx).html(amount.toFixed(2));
});
}
);
I think the problem was here [name^="Count_"]' you need a selector so change to this input[name^="Count_"]' and the anonimous function is not performed
$(document).ready(
(function() {
$(document).on('change','input[name^="Count_"]',function() {
console.log('here'); //not triggering on dynamic cell
var cell = $(this).attr('name');
var idx = cell.split('_')[1];
var amount = $(this).val() * $('[name="AvgCost_' + idx + '"]').html();
$('#ExtendedCostCell_' + idx).html(amount.toFixed(2));
});
}());
);
I moved the function outside of the document ready, and it now triggers on the dynamic rows.
I would like to know how to dynamically increase and decrease numbers in JavaScript.
The users buys an item and I have a input field "quantity" with a number and two buttons: One to add and another to remove.
My code is the following
<td class="quantity">
-
<input type="text" id="purchase_quantity" min="1" max="99" delta="0" cost="<?php echo$poupa ?>" name="purchase_quantity" value="1" />
<a href="#" class="addItem" >+</a>
</td>
How can I have it decrease the number of the input field when I click on the "-" and increase the number of the input field when clicking on the "+"?
var input = document.getElementById("YOUR_INPUT_ID");
function minus(){
var num = +input.value;//+ for convert from string to number
num--;
input.value = num;
}
function plus(){
var num = +input.value;//+ for convert from string to number
num++;
input.value = num;
}
http://jsfiddle.net/VY9tE/
One more example with your html form and with check count(0..99):
http://jsfiddle.net/VY9tE/2/
decrease:
-
increase
+
Assuming you can use jquery since you have it tagged.
Markup (changed the ID on the text input to a class):
<td class="quantity">
-
<input type="text" class="purchase_quantity" min="1" max="99" delta="0" cost="" name="purchase_quantity" value="1" />
+
</td>
JavaScript (uses jQuery):
$(function() {
$('.removeItem').click(function() {
// Find the appropriate quantity input
var target = $(this).siblings('.purchase_quantity');
// Get the current quantity
var currentQuantity = $(target).val();
// Not allowed to go below zero
if (currentQuantity > 0) {
// Update input with decreased quantity
$(target).val(--currentQuantity);
}
});
$('.addItem').click(function() {
// Find the appropriate quantity input
var target = $(this).siblings('.purchase_quantity');
// Get the current quantity
var currentQuantity = $(target).val();
// Update input with increased quantity
$(target).val(++currentQuantity);
});
});
See it in action.
I have a question about JQuery Min Max Validation looping through dynamic created input items.
In my php page i have a dynamic table who loops through the data in the DB.
Sometimes i have an table with 3 input Items (Cells) sometimes with 6 or 12 input items.
With jquery i found to validate min - max value of data, but it works only for the first input item.
How can loop throug all the input item to get the same min max validation?
Here the JQuery code:
$(document).ready(function(){
$("input").click(function(){
var enteredValue = $("input:#value_one").val();
var min=1;
var max = 3;
var num = parseInt(enteredValue);
if (min > num || max < num) {
alert('Number ' + num + ' is not a number between ' + min + ' and ' + max);
return false;
}
});
});
Here apart of the PHP HTML Code:
foreach($datas as $idactivite=>$dat){
$totalactiv=0;
$nbdiviseur=0;
foreach($dat as $dd){
$totalactiv+=$dd["note"];
$nbdiviseur++;
}
$mamoyactiv=$totalactiv/$nbdiviseur;
$position=3;
$mamoyactiv = substr($mamoyactiv, 0, $position);
$moyenneverticale[$idactivite]=$mamoyactiv;
// Here the input Item who loops through the DB Query to get them values:
$htmldroit.="<td id='myguaNote' bgcolor='$bgcolor' align='center'>
<input name='".$idactivite."_".$idagent."' id='value_one' maxlength='1' class='grand' value='".$dat[$idagent]["note"]."' ></td>";
$totalfamille+=$dat[$idagent]["note"];
$TabRes[$ind] += $dat[$idagent]["note"];
$TabObj[$ind] = " ";
$TabResColor[$ind]=0;
$ind++;
}
Somebody any ideas?
THX in advance
I think you're not really selecting the input field which was actually clicked.
Replace var enteredValue = $("input:#value_one").val() with
var enteredValue = $(this).val();
The callback function from click holds a reference to the clicked DOM element in the this keyword. wrap it in $() to make it a jQuery object and finally call val() on it.
Fiddle
Edit:
To validate multiple input fields on button click I used a helper class validate. Assuming all input fields you want to validate have this class you can bind some code to submit button's on click:
$("#submitButton").click(function(){
$(".validate").each(validateField);
});
First all elements having the class validate will be selected and on this collection we call jQuery's each() which takes a function handle as argument. This function (validateField in this case) should take to input arguments (index and element, see the documentation for more details - if you think of a strange for for a "for in"-loop you're not far off.).
I moved the your validation code in this function and simply replaced $(this) by $(element)
Fiddle
few tips
if you are working with dynamic data then don't use simple 'click' function, instead try .on ( with jQuery 1.7+)
$('document').on('click', 'input', function(){
var enteredValue = $(this).val();
//your rest of code
});
Try this
//========== Prototype to find out min value in an Array=========================
Array.prototype.min = function()
{
return Math.min.apply(null, this)
}
//============= Jquery Scripting===================================================
$selector=$("input"); //Your selector which is cursoring your inputs
$aryVal=new Array; //Define an Array
$selector.each(function() //Iterate to all the input
{
$aryVal.push(this.value); //push the value to array
});
var min = Math.min.apply(null, $aryVal); //Getting min value from array
alert(min);
It sounds like you might be looking for .on(), which will keep things up-to-date as the page changes, whereas the click you have is just on the state of the page when it's created. Try:
$("input").on("click",function(){
||
if (min > num || max < num) {
change to
// For a number not between min and max
if (num < min || num > max) {
// For a number between min and max
if (num >= min && num <= max) {
For testing:
<script>
function test(){
$html = document.getElementById("msg");
num = 100;
min = 10;
max = 100;
if (num < min || num > max) {
$html.innerHTML = "Num is not between min and max";
return;
}
if (num >= min && num <= max) {
$html.innerHTML = "Num is between min and max";
return;
}
}
</script>
<body onload="test()">
<div id="msg" style="border:1px solid #000000; height:100px">Answer has not been found!</div>
</body>
Good practice when creating a dynamic amount of elements which are being used to inject a variable somewhere is:
Give unique ID for identification.
Use CSS class. Class styles are meant to be repeated, ID's are not.
So if I were to generate a number of inputs 1 to 100
for ($i = 1; $i <= 100; $i++)
{
$IdAndName = "input" . $i;
echo("<input type='text' id='" . $IdAndName . "' name='" . $IdAndName . "' class='myStyle'/><br>\n");
}
Now you would have HTML elements with ID input1 to input100
You can then use the JQuery click event as you have, then use $(this).val() to retrieve it's value on click.
I have a table of data from mysql rendered on page via PHP into a HTML table.
Within this table of data, I have a row of data that should be focussed on (let's call it) row X.
I want the 2 rows above and below row X to be shown but all others hidden, as row X moves up and down, this would change (obviously) what was hidden, when row X is at the top/bottom I want to show 4 rows below/above.
I have done this with static content and JQuery, I am just unsure how to track row X and then apply the class names as required
I thought this was an interesting request so I threw up an example here. The interesting part is the selectors to select the siblings to display. Here is a function i wrote.
function rowXMoved()
{
// hide all rows besides rowX
$('.tableCSS tr:not(.rowX)').hide();
if($('.rowX').prev('tr').size() == 0)
{
// we are row number 1, show 4 more
$('.rowX').siblings('tr:lt(4)').show(); //:lt is less than(index)
}
else if($('.rowX').next('tr').size() == 0)
{
// we are the last row
// find the index of the tableRow to show.
var rowCount = $('.tableCSS tr').size();
$('.rowX').siblings('tr:gt(' + (rowCount - 6) +')').show(); //:gt is greater than(index)
}
else
{
// show 2 rows before and after the rowX
// there is probably a better way, but this is the most straight forward
$('.rowX').prev('tr').show().prev('tr').show();
$('.rowX').next('tr').show().next('tr').show();
}
}
You can show hide the normal way and based on the current row in focus change the innerHtml of the div in focus.
Lets say there are 4 divs holding four rows of data then if focus is on div 2 then it will contain row 2 data in inner html. As focus move or onchange the content in div 2 will keep changing based on which row is in focus. I hope the drift helps
You could give each row a class name, and set a click event handler. When the user clicks for the first time, hide the entire table except for the clicked row and four below if row < 4, four above if row > row.last-4, or two above and two below (if neither of the foregoing is true).
Basically it's dom manipulation so I'd take a look at the prev() and next() functions if I were you. You can get the number of rows in the table by doing, for example, $("table > tr").length.
Noah
Okay I have wrote an example that illustrates selecting different rows. Enter a number into the box (1 - 10) and click the button. Rows 1 or 10 will be shown (here you will change your class with jQuery or whatever) with one row above or below. Selecting other numbers (2 - 9) will show its self, and show one row above and one below.
Obvously this isn't exactly what you asked for - but it should illustrate the logic of how this can be done...
Enter row:
<input id="Text1" type="text" />
<input id="Button1" type="button" value="button" onClick="updateTable()"/>
<!-- Example table, note the Ids -->
<table id="yourTable">
<tr><td id="row1">Row 1</td></tr>
<tr><td id="row2">Row 2</td></tr>
<tr><td id="row3">Row 3</td></tr>
<tr><td id="row4">Row 4</td></tr>
<tr><td id="row5">Row 5</td></tr>
<tr><td id="row6">Row 6</td></tr>
<tr><td id="row7">Row 7</td></tr>
<tr><td id="row8">Row 8</td></tr>
<tr><td id="row9">Row 9</td></tr>
<tr><td id="row10">Row 10</td></tr>
</table>
<script type="text/javascript">
function updateTable()
{
var table = document.getElementById('yourTable');
var row = parseInt(document.getElementById('Text1').value);
var rows = table.rows.length;
// Reset the classes, styles etc etc for each row
for (var i = 0; i < rows; i++) {
table.rows[i].style.visibility = 'hidden';
}
// Subtract one as we start from 0.
row = row - 1;
// Top row, select the first and one below.
if (row == 0) {
table.rows[0].style.visibility = 'visible';
table.rows[1].style.visibility = 'visible';
}
// Rows in between. Select the middle, one above and one below.
if ((row > 0) && (row < rows - 1)) {
table.rows[row - 1].style.visibility = 'visible';
table.rows[row].style.visibility = 'visible';
table.rows[parseInt(row + 1)].style.visibility = 'visible';
}
// Bottom row, select the last row and one above that.
if (row == rows - 1) {
table.rows[row].style.visibility = 'visible';
table.rows[row - 1].style.visibility = 'visible';
}
}
</script>