Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

One types the number of Inputs they want and click GO, it creates that many number of input fields. How do I make it so each will have their own unique name?

I want to have unique names for each input created so ie:

  • 1st Inputs: name="productcode1"
    name="desc1" name="dollars1" name="cents1"
  • 2nd Inputs: name="productcode2"
    name="desc2" name="dollars2" name="cents2"

      $(document).ready(function(){
        $('#addButton').click(function(){
          var count = parseInt($('#quantity').val());
          var newHTML = [];
          for(var i=0;i<count;i++){
            newHTML.push('Product Code: <input name="productcode[]" type="text"/> &nbsp;&nbsp;Description: <input name="desc[]" type="text"/>&nbsp;&nbsp; $<input width="100px" type="text" name="dollars[]" size="5" maxlength="6"/>.<input width="50px" type="text" name="cents[]" size="1" maxlength="2"/><br/>');
          }
          $('#sandbox').html(newHTML.join(''));
        });
      });
    

FYI I'm also using PhP if it is easier to be incorporated

share|improve this question

1 Answer 1

up vote 0 down vote accepted

You can what is on this fiddle:

$(document).ready(function(){
        var numberOfInputs = 0;
        $('#addButton').click(function(){

          var count = parseInt($('#quantity').val());
          var newHTML = [];
          for(var i=0;i<count;i++){
            var html = $('Product Code: <input name="productcode" type="text"/> &nbsp;&nbsp;Description: <input name="desc" type="text"/>&nbsp;&nbsp; $<input width="100px" type="text" name="dollars" size="5" maxlength="6"/>.<input width="50px" type="text" name="cents" size="1" maxlength="2"/><br/>');
            $(html[0]).attr('name',$(html[0]).attr('name')+numberOfInputs);
            $(html[2]).attr('name',$(html[2]).attr('name')+numberOfInputs);
            $(html[4]).attr('name',$(html[4]).attr('name')+numberOfInputs);
            $(html[6]).attr('name',$(html[6]).attr('name')+numberOfInputs);
            numberOfInputs++
            newHTML.push(html);
            $('#sandbox').append(html);
          }

        });
  });
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.