Jquery each loop not working - javascript

I'm a newbie to jquery, but am trying to use it in my project.
I'm trying to loop through all the links inside #rate_box and add a click event to them. This click event will post some data to an external php script, and then it should unbind the click events on all of the links (so people cannot rate twice in quick succession.) Then it should put the data recieved from the php script into a span tag called #status.
However my code isn't even executing the alert("Index: "+i). Am I binding it correctly?
<script type="text/javascript">
$(document).ready(function(){
$('#rate_box a').each(function(i) {
$(this).click(function() {
alert("Index: "+i);
$.post("../includes/process/rating.php", {id: "<?php $game_id ?>", type: "game", rating: i+1},
function(data) {
$('#rate_box a').each(function(i) {
$(this).unbind('click');
}
$('#status').html(data).fadeIn("normal");
});
});
});
});
</script>

You don't need to loop through each link binding a handler individually, you can just do this:
// bind click handler to all <a> tags inside #rate_box
$('#rate_box a').click(function() {
});
Same goes for unbinding:
$('#rate_box a').unbind('click');
As far as your code, it probably isn't executing because you have not closed the inner each when you are unbinding the element tags, so it is invalid javascript:
$('#rate_box a').each(function(i) {
$(this).unbind('click');
} // <- missing closing ");"
You should really use a tool like Firebug or Firebug Lite to debug your javascript, although something like the above should just give you a Javascript error in most browsers.
EDIT If you want to find the index of the current link when it is clicked upon, you do this:
var links = $('#rate_box a');
$(links).click(function() {
// this is to stop successive clicks on ratings,
// although the server should still validate to make
// sure only one rating is sent per game
if($(this).hasClass('inactive_for_click')) return false;
$(links).addClass('inactive_for_click');
// get the index of the link relative to the rest, add 1
var index = $(links).index(this) + 1;
$.post("../includes/process/rating.php", {
id: "<?php $game_id ?>",
type: "game",
rating: index
}, function(data) {
$('#status').html(data).fadeIn("normal");
// unbind links to disable further voting
$(links).unbind('click');
});
});

Related

How to hide the anchor tag element rapidly on the onclick event using jQuery?

I've two hyperlinks. I'm hiding the one hyperlink on the click of other hyperlink and vice-versa. It's working absolutely fine for me on my local machine. But the issue arises when I upload and run the same functionality from the online server.
On server, the concerned hyperlink is not hiding that much quicker as compared to local machine instance. Due to which user can click again on a hyperlink which he has already clicked and the link is expected to be hidden. It takes moment or two for hiding the concerned hyperlink. I don't want that delay. The hyperlink should get hide immediately after on click event. I tried disable/enable the hyperlink but it didn't work out for me.
My code is as below:
<script language="javascript" type="text/javascript">
$(".fixed").click(function(e) {
var action_url1 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$(".fixed").colorbox({inline:true, width:666});
$("#fixedPop_url").off('click').on('click',function(event) {
event.preventDefault();
$.get(action_url1, function(data) {
//$("#fix_"+qid).bind('click', false);
$("#fix_"+qid).hide();//This portion of code I want to make fast, it's taking some time to hide and meanwhile user can click on this link. I want to avoid it.
$("#notfix_"+qid).show();
//$("#notfix_"+qid).bind('click', true);
alert("Question status updated successfully");
});
});
$(".c-btn").bind('click', function(){
$.colorbox.close();
});
});
$(".notfixed").click(function(e) {
var action_url2 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$(".notfixed").colorbox({inline:true, width:666});
$("#notfixedPop_url").off('click').on('click',function(event){
event.preventDefault();
$.get(action_url2, function(data) {
//$("#notfix_"+qid).bind('click', false);
$("#notfix_"+qid).hide();//This portion of code I want to make fast, it's taking some time to hide and meanwhile user can click on this link. I want to avoid it.
$("#fix_"+qid).show();
//$("#fix_"+qid).bind('click', true);
alert("Question status updated successfully");
});
});
</script>
You dont have to write the hide part code in complete function of get request. On live it will take time to fetch the rspond.so just keep it outside get function.something like this:
$(".fixed").click(function(e) {
var action_url1 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$("#fix_"+qid).hide();
//rest code......
});
$(".notfixed").click(function(e) {
var action_url2 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$("#notfix_"+qid).hide();//hide it here
//rest code......
});

Using ajax with Hyperlinks

I've created a bookmark page that retrieves links from a database and displays it. I'm able to log in, add new links & delete them. However, when I delete an entry it displays delete.php instead of loading the page onto itself (the query does work).
I've most likely over-complicated my code at this point and am probably overlooking something simple, as I've used a lot of JavaScript for other elements of the page.
The entries are added dynamically so this part of the HTML is being appended:
<h2>
[x]
</h2>
<a href="'+url+'" target="iFrame" class="linkURL">
<div class="bookmark">
<h3 style="float: left;">'+title+'</h3>
<br />
<p>'+desc+'</p>
</div>
</a>
JavaScript:
// DELETE FUNCTION
$("h2 a").click(function() {
return false;
var action = $(this).attr('href');
var form_data = {
URL: $("#linkURL").attr('href'),
is_ajax: 1
}; // form_data
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response){
if(response == 'success') {
alert('Successful delete!');
} else { // if
alert('Delete failed.');
} // else
} // function(response)
}); // ajax
return false;
}); // h2
The page is located here: http://samaradionne.com/links6/ if it is easier to view the whole thing.
You are using both an anchor tag a and a click event. You are getting the actual delete.php page because when you click on the anchor tag it works just like any regular link. You have no where in your code something that says "hey, don't actually follow this link like normal".
To not follow the link, you need
[x]
Furthermore, you attached your jQuery click event to the h2, which is not bad in of itself, just confusing as the intent is to actually click the link. In that case, you need:
$("h2 a").click(function(){});
Lastly, to bring this all together, you could do the following:
$("h2 a").click(function(){
// your normal logic
return false; // don't follow link
});
And then you don't have to have the onclick inside the anchor tag.
Since my links were dynamically generated, my .h2 a click was attaching itself to something that wasn't there yet. I added an event trigger to my append function that calls to my delete function.
Problem solved.

Javascript - how do I minimise this code example?

a quick question.
At the moment I have 12 links on a page, and 12 corresponding javascript codes that run when a each button is clicked.
I know 100% there must be a method of having 1 javascript code and the link passing a variable to it, so I don't have to have 12 different codes.
EG. Here is a link I'm currently using:
Anatomical Pathology
And the Javascript function that is run when the link is clicked loads some html from a php script into a div which is previously defined as level2:
$('#button1').click(function() {
level2.load("http://hello/script.php?url=poodles");
});
What I'd really like to do is something like this with the link:
Anatomical Pathology
And the function something like this, so I only need the 1 function not 12:
$('#button1').click(function() {
level2.load("http://hello/script.php?url=' + passurl + '");
});
How do I go about getting the data from the link tag into javascript, and also how do I add this passed variable into the url I want the javascript to pull data in from?
passurl isn't standard attribute, you should use data-passurl
$('#button1').click(function() {
var passurl = $(this).data('passurl'); // or $(this).attr('data-passurl');
level2.load("http://hello/script.php?url=" + passurl);
});
Why don't you utilize your hash there...
Anatomical Pathology
In your script
$(".button").each(function() {
// get the hash and extract the part we want store it in this enclosure
var url = $(this).attr("href").replace(/^#\//, "");
// create a click handler that loads the url
$(this).click(function() {
level2.load("http://hello/script.php?url=" + url);
});
});
This also brings about the possibility to extrapolate from that so that a hash passed through the url can also operate the script loading...
You can use the rel attributte (or any data- attributes if your using HTML5 Doctype) to save your URL and add a class to the links you want to execute your callback.
Anatomical Pathology
Your Callback:
$('a.button').click(function() {
level2.load("http://hello/script.php?url=' + $(this).attr('rel') + '");
});
For a more extensible solution you could consider making a json structure for your urls:
var urls = [{
"poodle":{
"url":"http://hello/script.php?url=poodle",
"someOtherData":"data"
},
"otherDog":{
"url":"http://hello/script.php?url=otherDog",
"someOtherData":"data"
}
}];
You would store some sort of key somewhere in your HTML element:
Anatomical Pathology
Then you would leverage this data structure in your functional code:
$('a').click(function () {
var key = $(this).attr('rel');
level2.load(urls[key].url);
});
As per Stuie, add a class to the links so that you can target them all at once. However, I don't see the need to fool with the hash, and I wouldn't add a bunch of click events either. Just delegate once and you're done:
<div id="wrapper">
Poodles
Schnausers
</div>
and the JS:
$('#wrapper').delegate('a.button', 'click', function(e) {
e.preventDefault();
var passurl = $(this).attr("href");
level2.load("http://hello/script.php?url=" + passurl); // assuming "level2" is valid from elsewhere
});
Where I have "#wrapper" you would designate any unique selector that is an ancestor of all your links. It's an element that listens for clicks on the a.button elements within.

How to Separate Two jQuery Functions

I want to separate these functions. They should both work separately on click events:
FIRST FUNCTION
$("ul.nav li").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
ACTION A
});
$(window).trigger('hashchange');
});
SECOND FUNCTION
$("ul.subnav li").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
ACTION B
});
$(window).trigger('hashchange');
});
This is what happend in ACTION A:
$mainContent
.find(".maincontent")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " .maincontent", function() {
$mainContent.fadeIn(200, function() {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
});
$(".nav a").removeClass("active");
$(".nav a[href="+newHash+"]").addClass("active");
});
});
The Problem is that if I click the Link of the Second function always the the first function fires.
Details of what I'm trying to do:
First, I build my site on .php to serve poeple without JavaScript. Now I want to load the "maincontent" dynamically. So I found this script I'm using:
http://css-tricks.com/6336-dynamic-page-replacing-content/
It does do a great job if you only want to load "maincontents".
But my site has sub-navigation on some pages where I want to load the sub-content. In .php these sites use includes. So I get my content by: href="page2.php?page=sub1"
So, when I click on the sub-links now they load also dynamically but the script also on the whole maincontent loading area. So it doesn't really load content by .load() but the sub-content of the includes do appear.
So what I thought was just to separate this function. The first to simply load the maincontents and a second one for the sub-navigation to refresh only the sub-content area. I don't even understand how this script loads the include content dynamically since the link is the straight page2.php?page=sub1 link. All dynamic loaded content usually looks like "#index", without the ending ".php".
Some quick history:
I'm trying to get the best page structure. Deliver .php for non JavaScript user and then put some dynamic loading stuff over it. Always with the goal to keep the browser navigation and the browser links (for sharing) for each page in tact.
I'm not an jQuery expert. All I have learned so far was by trial and error and some logical thinking. But of course, I have a lack of fundamental knowledge in JavaScript.
So my "logical" question:
How can I tell the "nav" links to perform only their "$(window).bind"-Event and to tell the "subnav" links only to perfom their "$(window).bin"-event.
Is this the right thinking?
Since I've already been trying to solve it for nearly the last 18h, I'll appreciate any kind of help.
Thank you.
IMPORTANT:
With the first function I not just only load the maincontent but also I'm changing a div on the page with every link. So for any solution that might want to put it together in one, it won't work, cause they should do different things on different areas on the page. That's why I really need to call on the window.bind with each nav/subnav click.
Can anyone show me how?
Melros,
In your second function, you are binding to the event hashchange2, which is incorrect. Instead, you STILL want to bind to hashchange. Instead of:
$(window).bind('hashchange2', function() {
...
});
Try:
$(window).bind('hashchange', function() {
...
});
If you want to namespace your event subscriptions, you can suffix the ending of the event you are binding to with a period (.) and then the namespace:
$("#test").bind("click.namespace1", function() { });
$("#test").bind("click.namespace2", function() { });
Ok, it seems that you want to execute action A when a link inside .nav is clicked, and action B when a link inside .subnav is clicked.
You can just put these actions inside the event handlers. Furthermor, if .subnav is nested inside .nav, you have to restrict your selector:
// consider only direct children
$("ul.nav > li").delegate("a", "click", function() {
var href = $(this).attr("href");
if(window.location.hash !== href) {
Action A
window.location.hash = $(this).attr("href");
}
return false;
});
// consider only direct children
$("ul.subnav > li").delegate("a", "click", function() {
var href = $(this).attr("href");
if(window.location.hash !== href) {
Action B
window.location.hash = $(this).attr("href");
}
return false;
});
I don't think listening to the hashchange event will help you here, as this event is triggered in both cases and you cannot know which element was responsible (you probably can somehow, but why make it overly complicated?).
Here's by the way the solution I came to:
After understanding that the haschange-event doesn't have to do anything with it (as long as you don't want to make the subcontent bookmarkable too) I just added a new load function for the subcontent:
$(function(){
$("ul.linkbox li a").live('click', function (e) {
newLink = $(this).attr("href");
e.preventDefault();
$(".textbox").find(".subcontent").fadeTo(200,0, function() {
$(".textbox").load(newLink + " .subcontent" , function() {
$(".subcontent").fadeTo(200,1, function() {
});
});
$("#wrapper").css("height","auto");
$("ul.linkbox li a").removeClass("activesub");
$("ul.linkbox li a[href='"+newLink+"']").addClass("activesub");
});
});
});

jQuery AJAX Request Repeating on Click event

Im building a small application and I have some click events binded to some span tags that trigger AJAX requests to a PHP file which queries a MySQL database and spits out the results to populate the targeted area.
However, sometimes i will be clicking the buttons and I have conditionals in place to stop multiple clicking to prevent duplicate content being added numerous times.
I click on a button and firebug tells me that the ajax request had actioned more than once, sometimes it will multiply - so it will start by doing it 2 times or another time it will carry our the request 8 times on one click and obviously flood my content area with duplicate data.
Any ideas?
EDIT
Code for a button is as follows:
<span class="btn"><b>Material</b></span>
This would be enabled by
$('.btn').bind('click', matOption);
and this would be controlled by something like this
var matOption = function() {
$(this).addClass('active');
// remove colours if change of mind on materials
if($('#selectedColour').val() >= 1) {
$('.colour').slideUp(500).children().remove();
$('#selectedColour').val('');
$('.matColOpt .btn').html('<b>Material Colour</b>').removeClass('active').css('opacity', 0.55);
$('.btn').eq(2).unbind('click', colOption); // add click to colour
$('#stage h1 span').eq(2).fadeOut(500);
$('.paperOpt .btn').css('opacity', 0.55).unbind('click', selectPaper);
}
// ajax req for available materials
var cid = $('#selectedColour').val();
var target = $('#notebookOpts .matOpt ul');
$.ajax({
type: "GET",
url: ajaxFile+"?method=getMaterials",
beforeSend: function() {if($('.mats').children('li').size() >= 1) { return false; }},
success: function(data) {
target.append(data).slideDown(500);
$('.mats li').bind('click', matSelect);
},
error: function() {alert('An unexpected error has occurred! Please try again.');}
});
};
You're probably binding your matOption function more than once.
if(!window.matOptionBound){
$('.btn').bind('click', matOption);
window.matOptionBound = true;
}
If you have a code that binds an event handler to a DOM element repeatedly then that event handler does gets executed repeatedly on the event. so if your code such
$("span").click(myHandlerFunction)
gets executed thrice, then you have just told jQuery to fire myHandlerFunction thrice on every click of span. It would be good to make sure there is no such condition goign on in your code. If that is not true then please post your code so that I can help further.
PS: The safest way to do this will be as
$("span").unbind("click",myHandlerFunction).bind("click",myHandlerFunction)

Categories