views:

38

answers:

4
+1  Q: 

jquery toggle help

I trying to use the toggle function, to change the background and href of a link, so far I have this code,

$('a.loveIt').toggle(
        function() {
         var url = $(this).attr('href');
         $.ajax({
            url:url,
            type:"POST",
            success:function(){
                //alert("hello");
                $('p#loveIt').append(
                    "<a class='lovedIt' href='<?php base_url()."welcome/noMore/".$row['contentId'];?>'>Change It</a>"
                )
                $('div#wrapper').append(
                    "<div id='flashAdded'><p>The content has been added to your content</p></div>"
                )
                $("#flashAdded").animate({marginTop:"0px"}, 1500);
                setTimeout(function () {$("#flashAdded").animate({marginTop:"-46px"}, 1500);}, 2000);
                $('.loveIt').removeClass('loveIt').addClass('lovedIt');
            }
         });
         return false
        },
        function() {
        alert(id);
            $(this).removeClass('lovedIt').addClass('loveIt')
        });

The URL variable that is being set in the first function is 'welcome/loveThis/5' 5 is different per article as it is the articles ID, on click the link I remove a class and add a class, but I also need to change the link href to 'welcome/noMore/5' (or whatever the id maybe).

Is this possible?

A: 

but I also need to change the link href to 'welcome/noMore/5' (or whatever the id maybe).

$('.loveIt').removeClass('loveIt').addClass('lovedIt').attr('href', 'welcome/noMore/5');

To add your link, just add .attr('href', 'welcome/noMore/5'); to it.

Sarfraz
A: 

Your PHP code won't be executed on each AJAX request, only when the page is sent to the browser the first time. Since all you are really doing is changing the "action" text, why not just use javascript string replacement instead?

$('p#loveIt').append( 
    "<a class='lovedIt' href='" + href.replace(/lovedIt/,'noMore') + "'>Change It</a>" 
);
tvanfosson
A: 

$(this).find('a').attr('href' $(this).find('a').attr('href').replace('loveThis','noMore') );

Replaces 'loveThis' with 'noMore' on matched a elements...

MQA
+2  A: 

I think you could try

var link = $('.loveIt');
link.removeClass('loveIt').addClass('lovedIt').attr('href', link.attr('href').replace('loveThis', 'noMore'));
Rune