The problem here is that page at alert has the final value of i.. any solution to this?
for(var i=start;i<=end;i++)
{
num=pageNumber.clone();
num.click(function(event)
{
event.preventDefault();
var page=i;
alert(page);
// drawPager();
});
num.find("span").text(i);
if(i==curPage) {
num.find("span").addClass("current");
num=num.find("span");
}
$("#pager>div").append(num);
}
You should do something like this:
num.click(function(i) {
return function(event) {
event.preventDefault();
var page = i;
alert(page);
}
}(i));
This would make an extra enclosure, so i wouldn't get overwritten.
You need to add the handler in a separate function that takes i as a parameter.
For example:
for(var i=start;i<=end;i++) {
handlePage(i);
}
function handlePage(i) {
num=pageNumber.clone();
num.click(function(event)
{
event.preventDefault();
var page=i;
alert(page);
// drawPager();
});
num.find("span").text(i);
if(i==curPage) {
num.find("span").addClass("current");
num=num.find("span");
}
$("#pager>div").append(num);
}
This way, a separate closure (with a separate i parameter) will be generated for each function call.
Related
I am trying to get the form values and display the values using html5 local storage
I have written html and js code but its not working
can you tell me how to fix it..
providing my code below
i have put in the fiddle too
https://jsfiddle.net/r977y9zb/2/
code
$(document).ready(function () {
function init() {
if (localStorage["name"]) {
$('#name').val(localStorage["name"]);
}
if (localStorage["email"]) {
$('#email').val(localStorage["email"]);
}
if (localStorage["message"]) {
$('#message').val(localStorage["message"]);
}
}
init();
});
$('.stored').keyup(function () {
localStorage[$(this).attr('name')] = $(this).val();
});
$('#localStorageTest').submit(function() {
localStorage.clear();
});
The only issue is your event handlers are not inside $(document).ready otherwise the code works fine:
$(document).ready(function() {
init();
});
function init() {
if (localStorage["name"]) {
$('#name').val(localStorage["name"]);
}
if (localStorage["email"]) {
$('#email').val(localStorage["email"]);
}
if (localStorage["message"]) {
$('#message').val(localStorage["message"]);
}
$('.stored').keyup(function() {
localStorage[$(this).attr('name')] = $(this).val();
});
$('#localStorageTest').submit(function() {
localStorage.clear();
});
}
DEMO
localStorage uses the .getItem() and .setItem() methods for accessing and setting stored data. You are passing your names directly to localStorage with brackets ([, ]) as if it were an array, which it is not.
As an aside, there is no need for your code to be wrapped in the init function, given that you only want to run the function once, when the page is ready.
Try this:
$(document).ready(function () {
if (localStorage.getItem("name")) {
$('#name').val(localStorage.getItem("name"));
}
if (localStorage.getItem("email")) {
$('#email').val(localStorage.getItem("email"));
}
if (localStorage.getItem("message")) {
$('#message').val(localStorage.getItem("message"));
}
$('.stored').keyup(function () {
localStorage.setItem($(this).attr('name')) = $(this).val();
});
$('#localStorageTest').submit(function() {
localStorage.clear();
});
});
I'm trying to create a function that adds an event to each button in a class. I have all of the buttons in an array and wanted to use Dustin Diaz's addevent() cross browser solution, but am unsure how to implement it. I'm used to using frameworks for this sort of thing, but have to use pure JS for this one.
Any pointers or advice on how to use Dustin's solution would be appreciated.
Ok so after taking #Pointy 's advice, I wrote this that checks for addEventListener and if not uses attachEvent This however is not calling testFunction(). What am I doing wrong here?
function addEvents()
{
var buttonArray=document.getElementsByClassName('mainButton');
for(i=0; i < buttonArray.length; i++)
{
if (i.addEventListener) {
i.addEventListener("click", testFunction);
}
else if (i.attachEvent) {
i.attachEvent("onclick", testFunction);
}
function testFunction() {
alert("Test");
}
}
// Attach an event to each button that when clicked on will display an alert that say 'Button X clicked' where X = the button ID
}
You are trying to add an event to a number. You should replace "i" with "buttonArray[i]" and add an else-case (defensive coding).
function addEvents() {
var buttonArray = document.getElementsByClassName('mainButton');
for(i = 0; i < buttonArray.length; i++) {
if (buttonArray[i].addEventListener) {
buttonArray[i].addEventListener("click", testFunction);
} else if (buttonArray[i].attachEvent) {
buttonArray[i].attachEvent("onclick", testFunction);
} else {
throw new Error("This should be unreachable");
}
}
function testFunction() {
alert("Test");
}
}
Like the title says, I would like to fill a variable up under some conditions
I thought I could do like that but no :
var content = $(function() {
if ($('#content').length) {
return $('#content');
}
if ($('#content_no_decoration').length) {
return $('#contenu_no_decoration');
}
if ($('#full_content').length) {
return $('#full_content');
}
if ($('#full_content_no_decoration').length) {
return $('#full_content_no_decoration');
}
});
So I thought that the javascript variable 'content' would be one of the jquery object representing an element in the dom. But it seems that 'content' is the function.
I guess you imagine what i want to do.. What is the syntax with JQuery ?
Thank you
$(function() { }) is short-code for the DOMReady event. You need to explicitly define a function, and then assign the return value to your variable.
For example:
function getObj()
{
if($('#content').length)
{
return $('#content');
}
if($('#content_no_decoration').length)
{
return $('#contenu_no_decoration');
}
if($('#full_content').length)
{
return $('#full_content');
}
if($('#full_content_no_decoration').length)
{
return $('#full_content_no_decoration');
}
}
You can then assign the value as :
var content = getObj();
You will need to call the assignment when the DOM is ready though, otherwise the selectors will not trigger as expected. For example:
$(function() {
var content = getObj();
});
You are only declaring the function, so content contains a pointer to the function.
Execute it and you are fine:
var content = function() {
if ($('#content').length) {
return $('#content');
}
if ($('#content_no_decoration').length) {
return $('#contenu_no_decoration');
}
if ($('#full_content').length) {
return $('#full_content');
}
if ($('#full_content_no_decoration').length) {
return $('#full_content_no_decoration');
}
}();
But you don't really need a function here. If the script tag is at the bottom of the page (right before the closing </body>-tag), or the assignment is within a load handler you could use:
var content = $('#content').length
? $('#content')
: $('#content_no_decoration').length
? $('#content_no_decoration')
: $('#full_content').length
? $('#full_content')
: $('#full_content_no_decoration').length
? $('#full_content_no_decoration')
: undefined;
Or use jQuery to your advantage and keep things really short:
var content =
$('#content,#content_no_decoration,#full_content,#full_content_no_decoration')
.get(0);
// if none of the elements exist, content will be undefined, otherwise
// it will contain [a JQuery Object of] the first existing element
why you don't do like that ?
function thatsAGoodName() {
if ($('#content').length) {
return $('#content');
}
if ($('#content_no_decoration').length) {
return $('#contenu_no_decoration');
}
if ($('#full_content').length) {
return $('#full_content');
}
if ($('#full_content_no_decoration').length) {
return $('#full_content_no_decoration');
}
}
var content = thatsAGoodName();
The function
$(function() {
// DOM safe to use do stuff
})
Is shorthand for the document ready event. This tells you the coder that the dom is safe to use.
You would not really return anything from this event.
content is an object because you're setting it to a object here:
var content = $(function() {
What you probably intended was:
var content;
if ($('#content').length) {
content = $('#content');
}
if ($('#content_no_decoration').length) {
content = $('#contenu_no_decoration'); // Is #contenu a typo???
}
if ($('#full_content').length) {
content = $('#full_content');
}
if ($('#full_content_no_decoration').length) {
content = $('#full_content_no_decoration');
}
Note, that this will have a reference to an element now. If you want the actual content you'll need to pull it out with something like html() or val().
You are using the shorthand for the jQuery ready event ($(function() {. What I believe you want is a self invoking function:
// remove the call to jQuery
var content = (function() {
if ($('#content').length) {
return $('#content');
}
// ... more
})(); // invoke the function, which should return a jQuery object
You may need to wrap this in a document.ready, depending on where your script is executed.
Rearrange it a little bit and it should work:
$(function () {
var content = (function() {
var regularContent = $('#content');
if (regularContent.length !== 0) {
return regularContent;
}
var contentNoDecoration = $('#content_no_decoration');
if (contentNoDecoration.length !== 0) {
return contentNoDecoration;
}
var fullContent = $('#full_content');
if (fullContent.length !== 0) {
return fullContent;
}
var fullContentNoDecoration = $('#full_content_no_decoration');
if (fullContentNoDecoration.length !== 0) {
return fullContentNoDecoration;
}
}());
});
This code is basically saying once the DOM is ready (the $(function () { ... }); part), run this anonymous function (the (function () { ... }()); part) and assign its return value to content.
Edit: Also, you're losing efficiency by running each of your selectors twice instead of just once.
It's true that content is the function, but you can use that function. Like:
var result = content();
Edit:
Remove the $() around var content = $({/* code */}) and it works.
I have a variable name that I pass into a plugin, but the variable is actually a function.
I use jquery $.isFunction to check if it is a function, and if it is, it should execute the function.
But I can't seem to make it work, I put some examples in jsfiddle:http://jsfiddle.net/tZ6U9/8/
But here is a sample code:
HTML
<a class="one" href="#">click</a><br />
<a class="two" href="#">click</a><br />
<a class="three" href="#">click</a><br />
JS
$(document).ready(function() {
help = function(var1) {
alert(var1);
}
function help2(var1) {
alert(var1);
}
$('a.one').click(function() {
var functionName = "help";
if ($.isFunction([functionName])) {[functionName]("hello");
} else {
alert("not a function");
}
return false;
});
$('a.two').click(function() {
var functionName = "help";
if ($.isFunction(functionName)) {
functionName("hello");
} else {
alert("not a function");
}
return false;
});
$('a.three').click(function() {
var functionName = "help2";
if ($.isFunction(functionName)) {
functionName("hello");
} else {
alert("not a function");
}
return false;
});
$('a.four').click(function() {
var functionName = "help2";
if ($.isFunction([functionName])) {[functionName]("hello");
} else {
alert("not a function");
}
return false;
});
});
As you can see, I tired a bunch of things, but all the wrong ones probably...
I inspired some of them from: jQuery - use variable as function name
Overall
I'm passing a variable that has the same name as a function, using jquery to check if it is a function, if it is, it should execute the function.
Thanks in advance for your help.
If you are wanting to call a function by a string of its name just use window.
var functionName = "help";
if ($.isFunction(window[functionName])) {
window[functionName]("hello");
} else {
alert("not a function");
}
You can use the following to invoke functions that are defined in the window/global scope, such as the function help:
if ($.isFunction(window[functionName])) {
window[functionName]("hello");
}
help2, on the other hand, is not accessible this way since you are defining it in a closure. A possibile solution is to define the function outside of the .ready() handler. Then, you can use window[functionName] to call it:
var namespace = {
help: function (var1) {
alert(var1);
},
help2: function (var1) {
alert(var1);
}
}
$(document).ready(function() {
var functionName = "help";
if ($.isFunction(namespace[functionName])) {
namespace[functionName]("hello");
}
});
DEMO.
Check Fiddle for the working example.
Example have only one link working. make other links similarly.
Edit: after first comment
HTML
<a class="one" href="#">click</a><br />
JS
var help = function(var1) {
alert(var1);
}
$(document).ready(function() {
$('a.one').click(function() {
var functionName = help;
if ($.isFunction(functionName)) {
functionName('test');
} else {
alert("not a function");
}
return false;
});
});
I would like to bind the same event to 3 checkboxes but with a different target each time:
var checkboxes = {
'selector1' : 'target1',
'selector2' : 'target2',
'selector3' : 'target3',
};
for (selector in checkboxes) {
var target = checkboxes[selector];
if (jQuery(selector).is(':checked')) {
jQuery(target).show();
}
else {
jQuery(target).hide();
}
jQuery(selector).bind('change', function() {
if ($(this).is(':checked')) {
jQuery(target).show();
}
else {
jQuery(target).hide();
}
});
};
But it doesn't work: on "change", the 3 selectors show/hide the 3rd target.
That's because the code in the event handler will use the variable target, not the value of the variable as it was when the event handler was created. When the event hander runs, the variable will contain the last value used in the loop.
Use an anonymous function to create a closure, that captures the value of the variable:
for (selector in checkboxes) {
var target = checkboxes[selector];
if (jQuery(selector).is(':checked')) {
jQuery(target).show();
} else {
jQuery(target).hide();
}
(function(target){
jQuery(selector).bind('change', function() {
if ($(this).is(':checked')) {
jQuery(target).show();
} else {
jQuery(target).hide();
}
});
})(target);
};
Side note: You can use the toggle method to make the code simpler:
for (selector in checkboxes) {
var target = checkboxes[selector];
jQuery(target).toggle(jQuery(selector).is(':checked'));
(function(target){
jQuery(selector).bind('change', function() {
jQuery(target).toggle($(this).is(':checked'));
});
})(target);
};
It doesn't work because target isn't scoped inside of a function. Blocks DO NOT provide scope in javascript.
But I've reduced it down for you and hopefully this will work out:
$.each(checkboxes, function(selector, target) {
$(selector).change(function () {
$(target).toggle($(selector).is(':checked'));
}).trigger('change');
});
target scope is the problem !
You could have simpler code:
use data for the handler
use .toggle(condition)
$.each(checkboxes, function(selector, target) {
$(selector).on('change', {target:target}, function (evt) {
$(evt.data.target).toggle($(this).is(':checked'));
}).change();
});