Hulk
Hulk

Reputation: 34200

dynamically add elements from jquery or javascript

if a user types in an input say 3 into a text box three small text boxes should be shown below or in a popup through javascript or jquery .How can this be done...

 <input type="text" name="order">3</input>

Thanks..

Upvotes: 0

Views: 421

Answers (2)

Gabe
Gabe

Reputation: 50523

Keep in mind you should probably mask the textbox to allow only numerical entries...Or maybe use a drop down list with a list of numbers to prevent error. But here is a great jquery mask plugin to prevent non-numerical entries.

<input type="text" name="Order" onKeyDown="checkVal(this)">3</input>

<div id="myDiv">
</div>


function checkVal(ctrl){
   var val = ctrl.value;
   $('myDiv').html(''); // remove existing elements
   for (i=0;i<parseInt(val,10);i++){
      $('#myDiv').append('<input type="text" />');
   }
}

Upvotes: 2

James
James

Reputation: 112000

Give the <input/> an id of "order", then it's as simple as:

var order = $('#order'),
    container = $('<div/>').insertAfter(order);

order.keyup(function(){
    container.html(
        Array(Math.abs(~~this.value) + 1).join('<input/>')
    );
});

FYI, ~~ (double-bitwise-not) has the effect of getting the number representation of any type (using the internal toInt32 operation) and then flooring it. E.g:

~~'2'; // => 2
~~'2.333'; // => 2
~~null; // => 0

And Math.abs is to protect against negative values, that will throw an error if passed to Array().

DEMO: http://jsbin.com/azexa4

Upvotes: 8

Related Questions