bart2puck
bart2puck

Reputation: 2522

dynamically added form element ids not found

I have a form in which a user can click a button and add additional fields as needed. Later on, user clicks submit, i do some error checking via ajax. if the additional fields are blank, i want to highlight them in red to let user know its required data.

jquery to add row:

  $('#addPerson').click(function(){
  var row = "<div id='row_"+rowNum+"'><div class='leftBigRow'><input type='text' class='field' id='addPerson[name][]' name='addPerson[name][]' placeholder='persons name'></div>";
  $('.additionalPeople').append(row);
  rowNum++;

my ajax call returns a string of field ids that have errors. for example result could be:

 //firstname,lastName,zipCode,...etc

so my errorcheck is:

 if(result.length > 0)
     {
       var errors = result.split(",");
       for (i=1;i<errors.length;i++)
       {
        alert(errors[i]);
        $('#'+errors[i]).addClass('error');
        alert($('#'+errors[i]).val());
       }
       $("#subForm").attr("disabled", "disabled");
      }

the first alert returns what i would expect "addPerson[name][0]"; the second alert returns undefined. telling me it cant find that field....

i have added a fiddle:fiddle

in my fiddle var result is a representation of what i get back from the ajax call. my ultimate goal is to get each field added by pressing yes to turn red if blank....

Upvotes: 0

Views: 75

Answers (3)

Igor
Igor

Reputation: 15893

You don't have an element with id equal to "addPerson[name][0]". When adding new input elements to DOM, you have to include rowNum in their id and name attributes.

Do not include "[" and "]" in name/id attributes. Use:

var row = "<div id='row_"+rowNum+"'><div class='leftBigRow'><input type='text' class='field' id='addPerson_name_"+rowNum+"' name='addPerson_name_"+rowNum+"' placeholder='persons name'></div>";

Upvotes: 1

Blaise
Blaise

Reputation: 22212

Use .on to bind later created DOM elements.

http://api.jquery.com/on/

Upvotes: 0

Riten Vagadiya
Riten Vagadiya

Reputation: 123

When you declare your dynamic element's id, you cannot use an array there. You can concatenate it with the rowNum count that you already have.

I have updated your JSFiddle here: http://jsfiddle.net/Myra4/3/

(Observe how I changed the dynamic element's id and your simulated 'result' variable)

I did it in JSFiddle for you so you can immediately verify that it works.

Upvotes: 1

Related Questions