0

I need to increase my input name if this already exists. When it exists it has to put an index number after the name.

Something like: selectboxvalue1, selectboxvalue2 etc. I had something in mind like this, but I can't figure out a simple solution.

if(jQuery('input[name="selectboxvalue"]').length > 0){

}
Nick
  • 425
  • 3
  • 9

1 Answers1

2

A more convenient way

Depending upon what you are using this for you can make use of HTML arrays. This allows you to declare an inputs name as selectboxvalue[] and when the form is submitted you will get the inputs back as an array of values.

Depending up on the language you are using to process the form this may or may not be handled natively. PHP does - please see the docs.

Direct answer

var selectIndex = 1;

function createInput() {
    if(jQuery('input[name="selectboxvalue"]').length > 0){
        var selectbox = jQuery('<input>', { name: 'selectboxvalue' + selectIndex, type: 'checkbox' });
        jQuery('blah').append(selectbox);
        selectIndex++;
    }
}
Treffynnon
  • 21,365
  • 6
  • 65
  • 98