serialise form with dynamic textboxes

I have created a for loop that allows me to produce textboxes for a user to input data to add to a mySql database.

var $frm2 = $("<form id=insertform class=form2></form>"); // craete the form $frm2.append(txt8, txt9); // add 2 clone dropdown boxes to the form  // this loop creates n number of text boxes abnd adds them to the form  for(var i = 0; i < n-1; i++)  {      $('<input /></br>', {         id: "valueid" + i,         text: "text",         name: "user"     }).appendTo($frm2); } 

The problem is when I serialise the data to AJAX post via JSON only the two drop boxes are serialised, the textboxes don't seem to add to the data.

$("#inserthbtn").click(function() {     var datastring = $($frm2).serialize();     $("#reports4").append(datastring);     alert(datastring); }); 

serialise form with dynamic textboxes

If u can see where I'm going wrong that would be amazing (I also know I am missing the script to post to AJAX, I couldn't get this to work so removed as part of fault finding process).

Replay

Give the inputs array-style names ending in []. When it's serialized, they will be collected into an array.

for(var i = 0; i < n-1; i++)
{
        $('<input />', {id: "valueid" + i,text: "text",name: "user[]"}).appendTo($frm2);
        $('<br />').appendTo($frm2);
}

Also, you can't use the object argument to $() to specify attributes of the new element when you put multiple elements into the first argument.

Another option is to give them unique names, name: "user"+i.

The issue is because although you provide an object with the properties to apply to the input you dynamically create, you're creating two elements (the input and br) therefore jQuery isn't sure which element you want to put the properties on. Remove the br element from the selector and it will work:

for(var i = 0; i < n-1; i++)  {
    $('<input />', {
        id: "valueid" + i,
        text: "text",
        name: "user"
    }).appendTo($frm2);
}

Category: javascript Time: 2016-01-26 Views: 0

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.135 (s). 12 q(s)