Obsivus
Obsivus

Reputation: 8359

How can I make sure that my click function executes one time only with Jquery?

I have jquery code that runs everytime everytime I click on my button but I only want it do do the stuff inside the click function once.. Beacuse otherwise my jquery code will duplicate values in my tbody td.

Here is my jquery code:

  $(function () {
        $('#next-step').click(function () {
            $('#S').append($('#SubjectTypeName option:selected').text());
            $('#T').append($('#TeamName option:selected').text());
            $('#C').append($('#ConsultantName option:selected').text());
            $('#K').append($('#company option:selected').text());
            $('#KP').append($('#ContactPerson').val());
            $('#P').append($('#date').val());
        });

    });

And here is the jsfiddle: http://jsfiddle.net/82U2W/

Any help is appreciated.

Thanks in advance!

Upvotes: 0

Views: 491

Answers (3)

Christian Eric Paran
Christian Eric Paran

Reputation: 1010

use a variable that would control the button when clicked.

$(function () {
    $('#next-step').click(function () {
        if(cmdCtrl){
           $('#S').append($('#SubjectTypeName option:selected').text());
           $('#T').append($('#TeamName option:selected').text());
           $('#C').append($('#ConsultantName option:selected').text());
           $('#K').append($('#company option:selected').text());
           $('#KP').append($('#ContactPerson').val());
           $('#P').append($('#date').val());
        cmdCtrl=false;
        }
    });

});

Upvotes: 0

Daff
Daff

Reputation: 44215

I would say the easiest way is to use jQuery.one:

 $(function () {
        $('#next-step').one('click', function () {
            $('#S').append($('#SubjectTypeName option:selected').text());
            $('#T').append($('#TeamName option:selected').text());
            $('#C').append($('#ConsultantName option:selected').text());
            $('#K').append($('#company option:selected').text());
            $('#KP').append($('#ContactPerson').val());
            $('#P').append($('#date').val());
        });

    });

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

I am not sure if I understood correctly, try .one if you want to execute the handler only once

$(function() {
    $('#next-step').one('click', function() {
        $('#S').append($('#1 option:selected').text());
        $('#C').append($('#2').val());
        $('#T').append($('#3').val());
    });
});

DEMO

Or perhaps you want the value to be copied over instead of appending then try like below,

$(function() {
    var copiedText = 'Copied Value: ';
    $('#next-step').on('click', function() {
        $('#S').text(copiedText + $('#1 option:selected').text());
        $('#C').text(copiedText +$('#2').val());
        $('#T').text(copiedText +$('#3').val());
    });
});

DEMO

Upvotes: 2

Related Questions