Looping through Input Items to get Min Max Value - php

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.

Related

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.

add values of multiple input boxes in Jquery

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

Ajax counter doesn't work

All,
I'm working with this Ajax tutorial which basically pull some records from a database and display them. I want to modify the code with a button that will show the records one by one instead of together. The behavior I want to achieve is to get the next record each time the user clicks the Show next button.
To do that I have built a little counter in the Ajax function that is used as an index to decide which array element to print. This doesn't work. **My question is: why doesn't my counter work?
Here is the html and Ajax code:
<html>
<body>
<script type="text/javascript">
<!--
function createRequest() {
//Returns HttpRequest
return request;
}
//My attempt at a counter. This doesn't work.
var index=null;
function calcIndex(){
if(index==null){
index=0;
}else{
index += index;
}
return index;
}
(.....)
</body>
</html>
Your calcIndex function declaration is broken, it's missing the function part. And are you sure you want to set index += index? That would be sort of odd. Not only that, even if you fix it and leave it as-is, index will never increment past zero:
var index=null;
function calcIndex(){
if(index==null){
index=0; // First call, now index = 0
}else{
index += index; // Second, third, ... nth call: index = 0 + 0
}
return index;
}
Let's simplify:
var index = 0;
function calcIndex(){
return index++; // Returns zero first, then 1, then 2...
}
But wait, at that point why do you need a function at all? Instead you can simply do:
var index = 0;
...
//index = calcIndex(); No point here
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex + "&index=" + index++;
^^^^^^^^
Cheers

compare values of cells in different rows in table using jquery

I have a dynamically generated table with php that has same rows. Need to get value from cell 1 in row 1 and value from cell 1 in row 2 and compare them. If they are the same remove entire row or hide... Do that for the whole table... Any help is appreciated.. Thanks!!
Haave this so far:
var numRows = $('table#changeSubjectKatedra tr').lenght;
var i = 0;
do {
var cur = $('input#'+i).val();
var next = $('input#'+(i+1)).val();
if(cur == next){
$('tr#'+i).remove();
}
i++;
} while(i<numRows);
The row in table looks like this:
<tr id='idNum'><td>someText<input type='hidden' value='someData' id='idNum'>
</td><td>someText</td></tr>
Note 1. You should do in on server side with PHP, not with JavaScript.
Note 2. You must use unique id for each element.
Note 3. Avoid using numerical ids of elements.
Note 4. You don't need ids at all for doing what you want.
If you still want to do it in JavaScript, I suggest you to do it this way: (live demo here)
var rows = $("#changeSubjectKatedra tr");
for(var i = 0; i <= rows.length - 2; i++) {
if ($(rows[i]).find("input").val() ==
$(rows[i+1]).find("input").val()) {
$(rows[i]).remove();
}
}
You can use jQuery's .each function. This should work according to the description you provided:
$('table#changeSubjectKatedra tr').each(function() {
if (repeat == $(this).children("input")[0].value) {
$(this).remove();
}
repeat = $(this).children("input")[0].value;
});

Total value with JavaScript and PHP

I'm using this form script to automatically calculate totals. Now I need to get that total and add it to a database via PHP and MySQL.
I don't know how to 'name' the totalPrice div, so that I can pass its value to the database.
Edit:
I'm still not getting results in the database. I'm now using $_POST[totalValue] for the field set and totalPrice for the field name.
HTML:
<div id="totalPrice"></div></div>
<input type="hidden" name="totalValue" id="totalValue" />
JavaScript:
$("#vendorform").submit(function(){
var totalValue = document.getElementById('totalValue');
totalValue.value = vendorPrice; //the actual total value
});
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var vendorPrice = getTentPrice() + getElecPrice() + getPropanePrice();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price Vendor $"+vendorPrice;
}
The vendorPrice variable is not available outside the scope of the function calculateTotal. You could make vendorPrice a global variable, but that's a bit of an ugly hack.
Alternatively, you could do something like this:
function calculateTotal()
{
var vendorPrice = getTentPrice() + getElecPrice() + getPropanePrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price Vendor $"+vendorPrice;
return vendorPrice; // <-- ADDED
}
And this:
$("#vendorform").submit(function(){
var totalValue = document.getElementById('totalValue');
totalValue.value = calculateTotal(); // <-- CHANGED
});
This way, you assign the value that is now returned by calculateTotal() to totalValue.value.
By the way: since it looks like you're already using jQuery, you can rewrite your code like this:
// [...]
var divobj = $('#totalPrice');
divobj.css('display', 'block');
divobj.text("Total Price Vendor $"+vendorPrice);
// [...]
var totalValue = $('#totalValue');
totalValue.val(calculateTotal());
This makes it a bit more readable (although that's debatable) and a bit more cross-browser reliant. jQuery has great docs (e.g. the documentation on .val()). If you're going to use jQuery more often I can highly recommend bookmarking the docs and skimming through them.
Using jQuery:
$("#cakeform").submit(function(){
var price = $("#totalPrice").text().replace(/[\s\S]+\$/,"")
$("#cakeForm").append('<input type="hidden" name="estimated_price" value="' + price + '" />')
})
But as #nick-rulez pointed out, is usually not a good idea to save calculated values in a database.
You can set the value to:
<input type="hidden" name="totalValue" id="totalValue" />
Which you have to put inside your <form>...</form>.
When you submit the form you're going to receive input's value.
You can set the value to the hidden field with this sniped:
JS
var totalValue = document.getElementById('totalValue');
totalValue.value = myValue; //myValue is the total
JavaScript:
function calculateTotal()
{
var Price = getTshirtPrice() + getTshirtType() + getTshirtColour() +
getTextColour();
var divobj = document.getElementById('textbox');
divobj.value = "Total Price For the T-shirt: £"+Price;
return Price;
}
HTML:
<div id="totalPrice"><input type="text" id="textbox"></div>
Do that. It works perfectly fine.

Categories