0

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);
            });
1
  • var newfun=$(function myfun(name,id){...your code}); Commented Mar 8, 2013 at 17:16

2 Answers 2

1

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) {...};
Sign up to request clarification or add additional context in comments.

Comments

0

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);
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.