views:

43

answers:

2
+2  Q: 

jquery click event

I have some jquery that looks like this,

    $('.career_select .selectitems').click(function(){
    var selectedCareer = $(this).attr('title');
    $.ajax({
        type: 'POST',
        url: '/roadmap/step_two',
        data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
        success: function(html){
            $('.hfeed').append(html);
            $('#grade_choice').SelectCustomizer();
          }
    });
});

My problem is that if the user keeps clicking then the .hfeed keeps getting data appended to it. How can I limit it so that it can only be clicked once?

+2  A: 

Use the one function:

Attach a handler to an event for the elements. The handler is executed at most once per element

If you wanted the element to only be clicked once and then be re-enabled once the request finishes, you could:

A) Keep a state variable that updates if a request is currently in progress and exits at the top of the event if it is.
B) Use one, put your code inside a function, and rebind upon completion of request.

The second option would look like this:

function myClickEvent() {
    var selectedCareer = $(this).attr('title');
    var that = this;

    $.ajax({
        type: 'POST',
        url: '/roadmap/step_two',
        data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
        success: function(html){
            $('.hfeed').append(html);
            $('#grade_choice').SelectCustomizer();
        },
        complete: function() {
            $(that).one('click', myClickEvent);
        }
    });
}

$('.career_select .selectitems').one('click', myClickEvent);
Paolo Bergantino
Also I wanted to mention `$.ajax` can provide `beforeSend` and `complete` callbacks to handle disabling/hiding controls, and provide better error recovery than `.one()` can.
Codesleuth
@Paulo could you give me an example of your answer B please?
sea_1987
A: 

You can either use a global variable like

var added = false;
$('.career_select .selectitems').click(function(){
    if(!added) {
        // previous code here
        added = true;
    }
});

or use .one("click", function () { ... }) instead of the previous click function to execute the handler at most once per element. See http://api.jquery.com/one/ for more details.

Viktor Stískala
Comment when you downvote, people!
Ender
I would also appreciate that
Viktor Stískala