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
Related
I have a table out of different MySQL data. I want to highlight cells with the same ID in it on hover. I did that with a simple jQuery, the script is almost working but you see I've got the var nr and want the integer i to be added to the class string. What is my mistake, why isn't it working? If you change the var nr = '.id_' + i; to a static variable like var nr = '.id_2'; it is working.
for (i = 0; i < 10; i++) {
var nr = '.id_' + i;
var bgcol = $(nr).css('backgroundColor');
$(nr).hover(
function(){
$(nr).css({"background":"yellow"});
},function(){
$(nr).css({"background":bgcol});
});
}
http://jsfiddle.net/Nkdny/210/
Solution, thanks to Karl-André Gagnon: http://jsfiddle.net/Nkdny/215 Look in the comments for details.
You're missing an echo in front of your php statement.
<?php echo $amount; ?>
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'm trying to update my database with some information. One of the key pieces of information is how much time has passed since the page first loaded and when the user click a button. My code looks like this:
<script>
function pauseVideo() {
$.get("video_pause.php?pause=" + timePassed + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
}
</script>
and
<html>
<div id="pause" onclick="pauseVideo()">PAUSE</div>
</html>
My PHP is fine so ignore that. The part I'm having trouble with is the 'timePassed'. I need this to be the amount of time in seconds since the page was first loaded and the person clicks the PAUSE div.
I think I need to run a function on click to find the passed time and then use that time variable in the $.get() somehow?
When the document loads, just save the current time in a variable:
$(document).ready(function() {
var timeWhenLoaded = (new Date).getTime() / 1000;
});
Then, when the pause button is clicked, calculate the time that has passed:
function pauseVideo() {
var currTime = (new Date).getTime() / 1000;
// time in seconds
var timePassed = Math.floor(currTime - timeWhenLoaded);
$.get("video_pause.php?pause=" + timePassed + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
}
Get rid of the onclick in your HTML, and remove your existing function, then put this in the head section of your page:
(function(){
var loadTime = (new Date).getTime(); // Page started loading
$(function(){
// DOM fully loaded, so move the assignment here if that is what
// you want to consider as the load time
$('#pause').click(function(){
$.get("video_pause.php?pause=" + Math.floor(((new Date).getTime() - loadTime)/1000) + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
});
});
})();
Also note that you can never trust that variable on the server side. Anyone could input a negative number or even the word 'pizza' for the value if they really want to.
Something like:
var startTime = (new Date).getTime() / 1000;
function pauseVideo() {
var curTime = (new Date).getTime() / 1000;
var timePassed = Math.floor(curTime - startTime);
$.get("video_pause.php?pause=" + timePassed + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
}
if the page with the following code is generated server-side, you can either just pass the current time to the script, as in:
<html>
<div id="pause" onclick="pauseVideo('" + curTime +"')">PAUSE</div>
</html>
(needs echo syntax)
or put it in a hidden field and pass it back to the server. (and do your calculations in php)
this way, you get the time passed since the page was requested...
I incorporate javascript in my PHP program:
Try to check my codes.
It loops depend on the number of records in database.
for instance:
$counter = 0;
foreach($row_value as $data):
echo $this->javascript($counter, $data->exrate, $data->tab);
endforeach;
private function javascript($counter=NULL, $exrate=NULL, $tab=NULL){
$js = "
<script type='text/javascript'>
$(function () {
var textBox0 = $('input:text[id$=quantity{$counter}]').keyup(foo);
var textBox1 = $('input:text[id$=mc{$counter}]').keyup(foo);
var textBox2 = $('input:text[id$=lc{$counter}]').keyup(foo);
function foo() {
var value0 = textBox0.val();
var value1 = textBox1.val();
var value2 = textBox2.val();
var sum = add(value1, value2) * (value0 * {$exrate});
$('input:text[id$=result{$counter}]').val(parseFloat(sum).toFixed(2));
// Compute Total Quantity
var qtotal = 0;
$('.quantity{$tab}').each(function() {
qtotal += Number($(this).val());
});
$('#tquantity{$tab}').text(qtotal);
// Compute MC UNIT
var mctotal = 0;
$('.mc{$tab}').each(function() {
mctotal += Number($(this).val());
});
$('#tmc{$tab}').text(mctotal);
// Compute LC UNIT
var lctotal = 0;
$('.lc{$tab}').each(function() {
lctotal += Number($(this).val());
});
$('#tlc{$tab}').text(lctotal);
// Compute Result
var result = 0;
$('.result{$tab}').each(function() {
result += Number($(this).val());
});
$('#tresult{$tab}').text(result);
}
function add() {
var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++) {
if (IsNumeric(arguments[i])) {
sum += parseFloat(arguments[i]);
}
}
return sum;
}
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
});
</script>
";
return $js;
}
When I running this on IE7 this message is always annoying me
Stop running this script?
A script on this page is causing your web browser to
run slowly. If it continues to run, your computer
might become unresponsive.
but in firefox it's functioning well.
IE displays that message when it decides that a script is taking too long (actually other browsers have a similar warning, but they don't all calculate "too long" the same way and don't all run at the same speed).
You didn't actually ask a question, but I assume you want to know how to make your script more efficient so that it will (we hope) complete before that IE message is triggered?
I like jQuery a lot, but using it does involve a lot of function calls, including nested functions with callbacks, etc., and once you start putting these functions inside loops (in your case multiple loops) it can get quite inefficient. If you're only processing a small number of items this may not be noticeable to the user, but if you're processing a lot the first thing you could change that would definitely speed up your code would be changing the .each() loops to standard for loops:
// CHANGE
var qtotal = 0;
$('.quantity{$tab}').each(function() {
qtotal += Number($(this).val());
});
// TO
var qtotal = 0,
$q = $('#tquantity{$tab}');
for (i = 0; i < $q.length; i++)
qtotal += +$q[i].value;
Note that in the for loop I've used the DOM element's value property directly rather than using jQuery to retrieve it via .val() (which even within .each() you could've done with this.value rather than $(this).val()). I've also used the unary plus operator instead of Number(). This means no function calls at all on loop iterations, whereas your way had a call to Number(), $() and .val() (not even counting the additional processing that jQuery does behind the scenes within $() and .val()).
Make a similar change for all of your .each() loops (declare i at the beginning of your function and re-use it for each loop) and you should see some improvement.
Hi i am new to ajax and trying to add two numbers in ajax function here is the code:
$("#next_btn").click(function(){
Display_Load();
var page = this.title;
var subtract = 1;
$("#content").load("pagination_brand.php?page=" + page, Hide_Load());
this.title = parseInt(page + 1);
});
in this function i am calling the div's title value and on click i want to add 1 value in to that number just like if title is having 1 so onclick it will become 2 but here its taking as string add when i see the output it disply 11 apart of 2.
It must be:
this.title = parseInt(page) + 1;
you need to do it like
for integers
parseInt(number1,10) + parseInt(1,10)
for floats/decimals
parseFloat(number1) + parseFloat(1,10)
Just parse the number then it will treat it like integer rather than string
this.title = parseInt(page)+1;