Skyalchemist
Skyalchemist

Reputation: 461

Submitting multiple fields data with ajax

So i have this http://jsfiddle.net/barmar/mDfQT/10/

$('.add_options').on('click', function () {
    $('#variants').append('<div class="some_id"><input type="text" id="prop_name" class="prop_name" placeholder="Property name"><a href="#" class="remover">Remove</a></div>');
    var size = parseInt($('#variants').attr("data-size"), 10) + 1;
    $('#variants').attr("data-size", size);
    $("#count").text(size);
});
$('#variants').on('click', '.remover', function () {
    $(this).closest('.some_id').hide();
    var size = parseInt($('#variants').attr("data-size"), 10) - 1;
    $('#variants').attr("data-size", size);
    $("#count").text(size);
});

Users can add as much fields as they want, after the user is done updating the values of the fields(number n), i would like to use ajax to submit the data. My question is, what's the most efficient way to get the data from all the textboxes while leaving each data field distinguishable(So that i can update my db). Ps:It's actually two text boxes per row, so when the user clicks add more it appends two texboxes(property name and property type) at once, the fiddle has only property name.
Thanks.

Upvotes: 0

Views: 422

Answers (2)

Shaddow
Shaddow

Reputation: 3215

There are some problems in your code

  1. ID is unique, only once per page
  2. Your HTML is not valid - ul tag shoud has only li tag
  3. If you want use .serialize method, your input must have name attribute

But if we forget this bugs here is solution:

$('input[name=submit]').click(function () {
    var data = $('#variants .prop_name').serialize();
    console.log(data);
});

jsFiddle code

Upvotes: 1

Mimo
Mimo

Reputation: 6075

Use the serialize jQuery function: http://api.jquery.com/serialize/

wrap the inputs in a form and then you can on submit serialize the data and post your ajax.

var dataToBeSubmitted = $('form').serialize()

Upvotes: 1

Related Questions