hi,
i'm trying to manipulate dynamic textboxes using jquery such that when the value of the textbox_1 is, say, 'abcd' a new text box textbox_2 would be introduced and when the value of textbox_2 is again 'abcd' a third one is introduced and so on. ive managed to do this with the following code, but with a little problem.

$(document).ready(function(){
    var cnt = 1;
    $("#inpu_"+cnt).keyup(function () {
        var value = $("#inpu_"+cnt).val();

        if(value == 'abcd'){
            $("#inpu_"+cnt).css("background-color", "red");
            cnt = cnt + 1;

            $("#content").append('<input type="text" id="inpu_' + cnt + '" />');
        }
     });

}).keyup();

the problem is that although textbox_2 is displayed instantaneously, the 3rd and 4th does not when the value of textbox_2 is 'abcd'. but they are displayed as soon as a key is pressed in the original textbox (textbox_1). that is the 3rd one is displayed when textbox_2's value is 'abcd' and a key is pressed while inside textbox_1. and so on.

[edit 1] btw, inside body tag ive created a div and given the id content. and inside it is the textbox_1 with the id 'inpu_1'. the original one that is.

what could be the problem? what am i doing wrong?
thanks in advance for ur help.

kekkaishi,

Here's a couple of ways to do what you want. First the HTML - it's best to use class rather than id as the selector, to avoid duplicate ids when we use jquery.clone() .

<div id="content">
    <input class="inpu" type="text" /><!-- no need for a counter -->
</div>

One way is to use jquery(sel).live() which binds your event handler to the existing textbox and future textboxes that match the same selector (sel). Thus, you don't need to keep track of things with cnt . Just start the ball rolling by selecting the original textbox and attaching the event handler.

$(".inpu").live('keyup', function() {
        if($(this).val() == 'abcd') {
            $(this).clone().val('').appendTo("#content").focus();
            $(this).css("background-color", "red").attr('disabled',true);
        }
	}).focus();

The second way is very similar but uses jquery(sel).bind() , and exploits clone(true) to create clones complete with the original's event handler.

$(".inpu").bind('keyup', function() {
        if($(this).val() == 'abcd') {
            $(this).clone(true).val('').appendTo("#content").focus();
            $(this).css("background-color", "red").attr('disabled',true);
        }
	}).focus();
});

Note 1: we clone before setting the red background otherwise the clone immediately has a red background too.
Note 2. .val() is necessary to nullify the value in the cloned textbox.
Note 3. .focus() is included twice to make testing quicker.

Airshow

thanks and much appreciated. :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.