Hi I am new to Jquery. I want to add two variables. Both are gloable variables.
Please see the "Add the variables" in the end of this code. The "cashupfirst" variable displays the value corectly but the "cashupsecond" variable says "undefined". But I can display the correct value of "cashupsecond" before this code. Please help.
jQuery(function($) {
var cashupfirst, cashupsecond;
var a, parent, input, doneLink, b, i, eq, c, z;
$(".Cashups").delegate("td:eq(3) > a", "click", function(event) {
//Index reading(not used here)
//var eq = $(this).parent().children("a").index(this);
// The `a` has been clicked; cancel the action as
// we're handling it
event.preventDefault();
event.stopPropagation();
// Remember it and its parent
a = $(this);
parent = a.parent();
// Insert an input in front of it, along with a done link
// because blur can be problematic
input = $("<input type='text' size='10'>");
input.insertBefore(a);
input.blur(doneHandler);
doneLink = $("<a href='#'>done</a>");
doneLink.insertBefore(a);
doneLink.click(doneHandler);
// Put the text of the link in the input
input.val(a.text());
// Temporarily detach the link from the DOM to get it
// out of the way
a.detach();
// Give the input focus, then wait for it to blur
input[0].focus();
// Our "done" handler
function doneHandler() {
// Replace the content of the original link with
// the updated content
a.text(input.val());
cashupfirst = a.text();
alert(cashupfirst);
//Set cookie to pass the text value to update it to table permanently
$.cookie('demoCookie',cashupfirst,{expires: 7, path: '/'});
// Put the link back, remove our input and other link
a.insertBefore(input);
input.remove();
doneLink.remove();
}
});
$(".Cashups").delegate("td:eq(9) > a", "click", function(event) {
// The `a` has been clicked; cancel the action as
// we're handling it
event.preventDefault();
event.stopPropagation();
// Remember it and its parent
a = $(this);
parent = a.parent();
// Insert an input in front of it, along with a done link
// because blur can be problematic
input = $("<input type='text' size='10'>");
input.insertBefore(a);
input.blur(doneHandler);
doneLink = $("<a href='#'>done</a>");
doneLink.insertBefore(a);
doneLink.click(doneHandler);
// Put the text of the link in the input
input.val(a.text());
// Temporarily detach the link from the DOM to get it
// out of the way
a.detach();
// Give the input focus, then wait for it to blur
input[0].focus();
// Our "done" handler
function doneHandler() {
// Replace the content of the original link with
// the updated content
a.text(input.val());
cashupsecond = a.text();
alert(cashupsecond);
//Set cookie to pass the text value to update it to table permanently
$.cookie('demoCookie1',cashupsecond,{expires: 7, path: '/'});
// Put the link back, remove our input and other link
a.insertBefore(input);
input.remove();
doneLink.remove();
}
//Add the variables
if (cashupfirst!= '' && cashupsecond!= '') {
alert(cashupfirst);
alert(cashupsecond);
var xyz = (parseInt(cashupfirst) + parseInt(cashupfirst));
jQuery('td#cashcalculator_total a').html(xyz);
}
});
//alert(cashupsecond);
});
Try
var xyz = parseInt(cashupfirst) + parseInt(cashupsecond);
The alert function does not return what has been alerted.
EDIT:
Okay, I see what's wrong. You must move the adding of the variables to inside the second doneHandler function, otherwise it won't wait until you have received a value for cashupsecond:
// Our "done" handler
function doneHandler() {
...
//Add the variables
if (cashupfirst!= '' && cashupsecond!= '') {
alert(cashupfirst);
alert(cashupsecond);
var xyz = parseInt(cashupfirst) + parseInt(cashupsecond);
jQuery('td#cashcalculator_total a').html(xyz);
}
}
// Don't add the variables here.
Related
I have uploaded a fiddle of my JS code (http://jsfiddle.net/3mcm2/), at the very bottom of which is the way in which I am calling the JS in my PHP document. In order to run the script, just remove the PHP code comments from the bottom. I just wanted to add that for you to see how I am outputting it in PHP. Also, above those last comments are three lines of comments in the .js file, which are there for you to see what it is that the PHP is echoing just to help you better understand how everything looks.
/* The following is what is in my .js file: (see the bottom of this script for part of
what is in my PHP file) */
var f = document.createElement("form");
f.setAttribute('method', "get");
f.setAttribute('action', "index.php");
var Category = (function () {
var categoryCount = 0;
function elem(tag) { // shortcut
return document.createElement(tag);
}
function text(str) { // shortcut
return document.createTextNode(str);
}
function Category(node) {
var self = this;
this.categoryId = ++categoryCount;
// make add button
this.addButton = elem('button');
this.addButton.appendChild(text('Add Textbox'));
this.addButton.addEventListener('click', function () {
self.addTextbox();
});
// make wrapper
this.wrapper = elem('section');
this.wrapper.setAttribute('id', 'cat'+this.categoryId);
this.wrapper.appendChild(this.addButton);
// make textboxes
this.textboxes = [];
this.addTextbox();
// append to document
if (node) {
this.append(node);
}
}
Category.prototype.addTextbox = function () {
var e = document.createElement("input");
e.setAttribute('name', 'cat-'+this.categoryId+'-textbox[]');
f.appendChild(e); // this is where each textbox is supposed to be added to the form...
this.textboxes.push(e);
this.wrapper.insertBefore(e, this.addButton);
};
Category.prototype.append = function (node) {
return node.appendChild(this.wrapper);
};
return Category;
}());
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(s);
//var cat1 = new Category(document.body);
//var cat2 = new Category(document.body);
//document.getElementsByTagName('body')[0].appendChild(f);
The above comment is only for you to see what this script is doing and those three lines are not actually in my .js file. the following comments are part of what is in my PHP file, pretty much just outputting the above comments:
$counter = 0;
echo '<script type="text/javascript" src="js/categories.js"></script>';
foreach ($catArr as $category) {
$counter++;
echo 'do<script>var cat'.$counter.' = new Category(document.body);</script>';
}
echo "<script>document.getElementsByTagName('body')[0].appendChild(f);</script>";
My problem is that with the form I created in the JS, the GET is not delivering any data. My php page is simply going from index.php to index.php? with the question mark, and not with any of the textbox variables following the question mark. For some reason, the form is not finding those textboxes that are created or their names. Please help me out.
This code:
var cat1 = new Category(document.body);
function Category(node) {
var self = this;
this.categoryId = ++categoryCount;
// make add button
this.addButton = elem('button');
this.addButton.appendChild(text('Add Textbox'));
this.addButton.addEventListener('click', function () {
self.addTextbox();
});
// make wrapper
this.wrapper = elem('section');
this.wrapper.setAttribute('id', 'cat'+this.categoryId);
this.wrapper.appendChild(this.addButton);
// make textboxes
this.textboxes = [];
this.addTextbox();
// append to document
if (node) {
this.appendChild(node);
}
}
appends all your input text boxes to the body and not the form, so when you press Submit no data is being passed
fiddle with working code: http://jsfiddle.net/5H8Pv/1/
I'm using the following to auto refresh the contents of a div.
$(document).ready(function() {
$("#log").load("test.php?q=" + $('#sq').val());
var refreshId = setInterval(function() {
$("#log").load("test.php?q=" + $('#sq').val());
}, 1000);
$.ajaxSetup({ cache: false });
});
This seems to work fine. I have a text field with the name 'sq' and anything entered in there is searched for by test.php.
My page also has 2 other form fields.
A checkbox and another text field. The checkbox has the id 'chk' and the text field 'txt'.
What I would like to do is change the URL being used by load() if the checkbox is ticked and a value is entered in the text field. Obviously this will also need to include 'sq'.
Can some one point me in the right direction.
The URL with out the check box being ticked is : ( is it is now )
test.php?q=VALUE_FROM_sq
With the checkbox ticked it needs to be :
test.php?s=1&txt=VALUE_FROM_txt&q=VALUE_FROM_sq
Then test.php can use $_REQUEST to get the values passed.
My network box only supports php4 so that does limit me some..
Can some one point me in the right direction. Thanks
Just add some logic in the code:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
var refreshId = setInterval(LoadLog, 1000);
LoadLog();
});
function LoadLog() {
var sq = $('#sq').val();
var text = $("#txt").val();
var url = "test.php?q=" + encodeURIComponent(sq);
if ($("#chk").is(":checked") && text.length > 0)
url += "&s=1&txt=" + encodeURIComponent(text);
$("#log").load(url);
}
You could save the URL in a separate variable and update it on the changed event of the checkbox.
var url = "test.php?q=VALUE_FROM_sq"
$(document.body).on('change', '#chk', function (event) {
if ($(this).is(':checked')) {
url = "test.php?s=1&txt=VALUE_FROM_txt&q=VALUE_FROM_sq"
} else {
url = "test.php?q=VALUE_FROM_sq"
}
}
My problem occurs, when I upload images with ajax. Ajax response comes to a hidden iframe, and for debug I echo it (uploaded image name) here and then alert it. So when I upload the first image - there's one alert, as it should be. When I upload the 2nd - I see 2 alerts. The 3rd - 3 alerts. And so on. It means, that my iframe reloads as many times, as the order number of the file being just uploaded.
Interesting, that the names in alerts after each file upload are always the same. For example, 2 times "mySecondImage.jpg", 3 times "myThirdImage.jpg"...
What can be done to solve the problem? Thanks.
// FUNCTION - AJAX FILE UPLOADER
// this function creates new elements, but only in case, when user uploads files
$.fn.fileUploader = function ( $inputName ) {
var $body = $(this);
var $form = $body.parents('form');
var $fileInput = $body.find(':file');
// after file is uploaded, we need the file input to be empty again
var $fileInputEmpty = '<input type="file" name="' + $inputName + '" />';
var $iframe = $('#ajaxResult');
// user submits the form
$form.submit( function() {
// check the result
$iframe.load( function () {
var $response = $iframe.contents().find('body').html();
alert($response); // debug
// add new content image
$output = createUpdateImage( $response, $('[name="imageLinkURL"]').val() );
// add new element
addNewElement( $output );
// success
if ( $response.length ) {
$fileInput.replaceWith( $fileInputEmpty );
$fileInput = $body.find(':file');
}
});
}); // form submit
};
$('.fileUploder').each(function () {
var $inputName = $(this).find(':file').attr('name');
$(this).fileUploader( $inputName );
});
Well, the glitch is fixed!
I slightly rewrote the jQuery function:
...
// user submits the form
$form.submit( function() {
var $response = '';
$iframe.load( function () {
$response = $iframe.contents().find('body').html();
});
// periodically check the result in iframe
var $timer = setInterval( function() {
if ( $response != '' ) {
clearInterval( $timer );
// do all required actions
}
}, 100 );
}); // form submit
...
$form.submit( function() {
$iframe.load( function () {
I think the problem is here. On form submit you add an event "on load". So it called 1 time, then 2 times, etc. Maybe removing the first of these two strings can help (use only load event handler).
I'm using this code:
<script type='text/javascript'>
$(document).ready(function () {
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
$('#ajax').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + document.location.hash.replace(/^.*#/, '');
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#ajax').html(html);
//display the body with fadeIn transition
$('#ajax').fadeIn('slow');
}
});
}
</script>
So I have to use: page to run the ajax ... However, I am using in some places:
Go to some <a href='#1'> notices </ a> for example ... And when you click, instead of just driving to the id = '1 ', is doing the ajax code to run.
How do I add an exception and not when you run the code number in the hash?
If you want to check the existence of a digit in your hash string, you can easily use RegExp.
This way you can create a pattern and check a string :
var pattern = new RegExp(/.*[0-9].*/);
pattern.test(hash); // Will return TRUE if it contains any digit.
You can add an exception by adding a check to see if the hash is an integer or not. See code below. (I've only adjusted the $('a[rel=ajax]') section, the rest of the code is fine as is.)
//Search for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
// test if hash is not an integer
if(parseInt(hash) != hash){
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
$('#ajax').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
}
});
I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/