SoFunction
Updated on 2025-03-01

Several ways to dynamically add data to forms and submit

Scenario 1: The form object already exists. Dynamically add objects to form and submit them

function formAppendSubmit(){
var myform=$('#newArticleForm'); //Get form objectvar tmpInput=$("<input type='text' name=''/>");
("value", ());
(tmpInput);
();
}

Scenario 2: There is no form object, form is generated dynamically, data is added dynamically and submitted

function(event){
form = $("<form></form>")
('action',action)
('method','post')
input1 = $("<input type='hidden' name='input1' />")
('value','input1 value')
input2 = $("<input type='text' name='textinput' value='text input' />")
(input1)
(input2)
("body")
('display','none')
()
}

jquery ajax submit form

$.ajax({
type: "POST", 
url: ,
data: $('#formId').serialize(),
success: function (data) {
},
error: function(data) {
}
});

jquery ajax non-form form

$.ajax({
type:"post",
url: "",
data: "name="+user + "&chatRoomId="+chatRoomId,
success:
function(){
},
error:
function(){
}
});

5|0 Scenario 3: There is no form object, use formData to dynamically add data and submit it

function UpladFile(fileUploadId, taskid) { 
 var fileObj = (fileUploadId).files[0]; // Get file object// FormData objectvar form_data = new FormData();
//("author", "hooyes"); // Can add form dataform_data.append("taskid", taskid);
form_data.append("file", fileObj); // File object $.ajax({
 type: "POST",
  dataType: "html",
  url: ,
  data: form_data,
  success: function (data) {
 },
  error: function(data) {
 }
});
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.