0

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..

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

Might be helpful for most readers if you explain the double bitwise NOT flooring. :)
2

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" />');
   }
}

9 Comments

Always specify the radix as the second parameter to parseInt. This ensures that input like 0xAF and similar input isn't parsed in an undesired radix
That is going to put 4 textboxes in the div, not 3. You need to change that to i<parseInt.
i<=parseInt(val) should be i<parseInt(val) ;)
Gah! What's with the obtrusive event handling?
@J-P its a simple example. I showed the logic of how to add the textboxes simply. The question didn't ask about anything regarding event handling. I'm betting he will use a submit button or something. Thanks for the down vote, unwarranted.
|

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.