简体   繁体   中英

How do I submit the same name textbox value through AJAX

I have many textboxes which are dynamically added through jQuery. they all have same name like...

<input type="text" name="employer" id="employer" />
<input type="text" name="position" id="position" />
<input type="text" name="city" id="city" />

<input type="text" name="employer" id="employer" />
<input type="text" name="position" id="position" />
<input type="text" name="city" id="city" />

so many...

I am passing all textbox value through AJAX, but its not working. my AJAX code is below..

AJAX

$.ajax(
    {
      type: "POST",
      url: $("#cfgRoot").val()+'/accounts/educationInfoPost.php',
      data:
      {
        employer:$("#employer").val().trim(),
        position:$("#position").val().trim(),
        city:$("#city").val().trim()
      }
});

Thanks in Advance

var empName = $("input[name=employer]").map(function(){
   return $(this).val();
}).get().join(",");

And pass it into ajax data.

Code


var empName = $("input[name=employer]").map(function(){
   return $(this).val();
}).get().join(",");

var position = $("input[name=position]").map(function(){
   return $(this).val();
}).get().join(",");

var city = $("input[name=city]").map(function(){
   return $(this).val();
}).get().join(",");


$.ajax(
{
    type: "POST",
    url: $("#cfgRoot").val()+'/accounts/educationInfoPost.php',
    data:
    {
        employer:empName,
        position:position,
        city:city
    }
});

And one more thing DO NOT ADD SAME ID FOR DOM.

ID MUST BE UNIQUE FOR EACH DOM

What do you think happens when you give 2 inputs the same name and moreover, the same ID?

If you have multiple inputs, which you want as the same name, you should give them similar names at the least.

Something like

<input type="text" name="employer1" class="employer" />
<input type="text" name="position1" class="position" />
<input type="text" name="city1" class="city" />

Or, you could give them to an array

<input type="text" name="employer[]" class="employer" />
<input type="text" name="position[]" class="position" />
<input type="text" name="city[]" class="city" />

As far as sending this data through AJAX, you might just want to serialize the whole form. Of course, this is based on the assumption that you want to send ALL the form data in one go.

var serializedForm = $('form').serialize();
$.ajax(
{
    data: serializedForm,
    //rest of the code here
});

您的字段ID不是唯一的,请尝试使您的ID唯一,并且它应该有效。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM