chris_s
chris_s

Reputation: 1051

Creating a jQuery function from a block of code

How can I turn this code into a function where all I need to do is bind it to a div id, and pass in name and id parameters for the inputs?

            var startingNo = 3;
            var $node = "";
            for(varCount=0;varCount<=startingNo;varCount++){
                var displayCount = varCount+1;
                $node += '<p><input type="text" name="duties'+displayCount+'" id="duties'+displayCount+'"><span class="removeVar">Remove Variable</span></p>';
            }

            //add them to the DOM
            $('#duties').prepend($node);

            //remove a textfield
            $('#duties').on('click', '.removeVar', function(){
               $(this).parent().remove();
               varCount--;
            });

            //add a new node
            $('#addVar').on('click', function(){
            varCount++;
            $node = '<p><input type="text" name="duties'+varCount+'" id="duties'+varCount+'"><span class="removeVar">Remove Variable</span></p>';
            $(this).parent().before($node);
            });

Upvotes: 0

Views: 84

Answers (2)

Derek Henderson
Derek Henderson

Reputation: 9706

Do you mean you want a jQuery prototype function, something that behaves like $('div').doSomething(name, id);? In that case, it's:

$.fn.doSomething = function (name, id) {...};

Upvotes: 1

RMalke
RMalke

Reputation: 4094

I don't know if I get it correctly, but it is just concatenate in the tags creations and in jquery selector:

function myFunction(name, id) {
    var startingNo = 3;
    var $node = "";
    for(varCount = 0; varCount <= startingNo; varCount++) {
        var displayCount = varCount + 1;
        $node + = '<p><input type="text" name="' + name + displayCount + '" id="' + id + displayCount + '"><span class="removeVar">Remove Variable</span></p>';
    }

    //add them to the DOM
    $('#' + id).prepend($node);

    //remove a textfield
    $('#' + id).on('click', '.removeVar', function(){
       $(this).parent().remove();
       varCount--;
    });

    //add a new node
    $('#addVar').on('click', function(){
        varCount++;
        $node = '<p><input type="text" name="' + name + varCount + '" id="' + id + varCount + '"><span class="removeVar">Remove Variable</span></p>';
        $(this).parent().before($node);
    });
}

Upvotes: 0

Related Questions