-1

This bit of code below appends a div to another div. The former div contains an input element with the name attribute "inputName[]". I'm guessing this is an array that auto-increments as more divs are added. How can I output the length of this array? I tried to console.log it (as below), but it's not working.

The error I get is "Uncaught TypeError: Cannot read property 'length' of undefined"

What can I do to fix this please?

$("#buttonid4").on("click", function() {

    var string1 = "<div class='eight columns'>
       <input type='text' size='76' placeholder='paste URL here' name='inputName[]'> </div>";

        $("#deleteandadd").append(string1);                            

        console.log(inputName.length);

    });
thanks_in_advance
  • 2,603
  • 6
  • 28
  • 44
  • 1
    Where are you declaring the variable "inputName"? – Seano666 Sep 19 '14 at 03:53
  • @Seano666 I tried declaring it as "var inputName;" , both outside the "$("#buttonid4").on("click", function()", and also within it. I also tried "var inputName[];" but got an error for that. – thanks_in_advance Sep 19 '14 at 03:56
  • @Moogs JSFiddle here, thanks: http://jsfiddle.net/0yo7LLpk/ – thanks_in_advance Sep 19 '14 at 04:00
  • It's very unclear what this variable is even used for. You say it is an array but then you are using it as the name property for the element you are appending? You are doing nothing with an array in the code you've provided. Very confusing. – Seano666 Sep 19 '14 at 04:01
  • @Seano666 I was assuming that when it's used as the name property for the elements being appended, it automatically becomes an array (e.g. inputName[1], inputName[2] etc.). OK, I just want to know the count of how many input elements have been appended with the name inputName[]... what's the simplest way to do that. – thanks_in_advance Sep 19 '14 at 04:04

1 Answers1

6

if you want number of inputs with name "inputName[]" ,you can use name selecter in jquery.

like the following

$('#deleteandadd input[name="inputName[]"]').length

or

var  inputName=    $('#deleteandadd input[name="inputName[]"]')

console.log(inputName.length)
vimalpt
  • 551
  • 3
  • 16
  • 1
    Fantastic, that worked, thanks. I suppose that technically inputName[] is not really a javascript array, but is instead written that like for PHP purposes. – thanks_in_advance Sep 19 '14 at 04:06