Tommy
Tommy

Reputation: 697

jQuery - add several textboxes

Im using this code:

    jQuery.fn.update_textarea = function(test) { 
                $("#articles_textarea").html('');
                for (i=0;i<test;++i) { 
                    if (message[i]) { $("#articles_textarea").html('<textarea></textarea>'); }
                    else { message[i] = ''; $("#articles_textarea").html('<textarea></textarea>'); }
                }
            }

When im trying to add more then one, nothing happends but if i add 1 it works just as it should..

This is the "call"code

$("#articles_textarea").update_textarea(total);

This is variable total:

var total = parseFloat($(".testCounter").val()) + 5;

This is for calling only one textarea (the part that works):

$("#articles_textarea").update_textarea(1);

When i call one box it's working when i call several boxes nothing happends at all..

Upvotes: 0

Views: 45

Answers (2)

Mehran Hatami
Mehran Hatami

Reputation: 12961

Why you use jQuery.fn, when you don't use its functionality, whereas it works, only for the textareas with articles_textarea Id, you better do it using a simple function like:

function update_textarea(test) { 
    $("#articles_textarea").html('');
    for (var i=0;i<test;++i) { 
        if (!message[i]){
            message[i] = '';
        }
        $("#articles_textarea").append('<textarea></textarea>');
    }
};

adding a new function to jQuery.fn is used to create new jQuery plugins, check this link for more info. the other point was not using var i in your for loop which is not a good practice. Moreover both your if statement and the else, were the same, except message[i] = ''; part.

BTW if you want to do it using jQuery.fn, you better do it like:

jQuery.fn.update_textarea = function(test) { 
    this.html('');
    for (var i=0;i<test;++i) { 
        if (!message[i]){
            message[i] = '';
        }
        this.append('<textarea></textarea>');
    }
};

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

try with append method. .html() will remove the previous content

jQuery.fn.update_textarea = function(test) { 
            $("#articles_textarea").html('');
            for (i=0;i<test;++i) { 
                if (message[i]) { $("#articles_textarea").append('<textarea></textarea>'); }
                else { message[i] = ''; $("#articles_textarea").append('<textarea></textarea>'); }
            }
        }

Upvotes: 1

Related Questions