POST mulitple inputs in form with jQuery

2019-02-26 17:42发布

问题:

I generate some inputs that looks something like this in HTML:

<input id='estemated_days' type='text' data-id='717' value='6'>

<select id='elements_grade' data-id='717'>
 <option value='1'></option>
 <option value='2'></option>
 <option value='3'></option>
</select>

<input id='estemated_days' type='text' data-id='718' value='4'>

<select id='elements_grade' data-id='718'>
 <option value='1'></option>
 <option value='2'></option>
 <option value='3'></option>
</select>

I generate about 10 at the time but showing you two as an example. How can I POST multiple input values to an external PHP file using jQuery? Previously I have used something like this (see code below) when submiting post data but this only seem to work for single fields with an ID - not a database generated data-id

//Initiate function when user clicks save
$("#save_courseplan").click(function() {

//Store the values of the fields as variables
var elements_grade = $('#elements_grade').val();
var estemated_days = $('#estemated_days').val();


$.post('../update.php', {

    estemated_days: estemated_days, //This for example will now represent 6
    elements_grade: elements_grade //And this 1

    }, function(data) {
    $('#updatestatus').html(data); //Display what update.php echoes out
 });
});

EDIT

OK I don't think i was quite clear. I have dynamically created inputfields. These fields has a data-id wich is fetched from a MySQL database.

The database looks something like this:

+------------+------------+
| scpe_id    | scpe_days  |
+------------+------------+
| 717        | 6          |
+------------+------------+
| 718        | 4          |
+------------+------------+

Previously, I have been successful in updating single field based on the value it contains using the jQuery code i posted earlier in this thread. One ID contains a value, this value is beeing $_POST to my update.php file and then inserted in the database.

Now, however I cannot use ID, because I need to update mutiple rows at once, each with different database-ID.

So what I would like is to first fetch the value of the data-id, to know what row to update, then fetch the value it holds to know what to be inserted - and then repeat for every <input>.

回答1:

var queryString = $('form').serialize();

Done.

Notes:

  • Make sure all the form elements, are inside the form element.
  • All the form elements must have a name attribute .

serialize docs

Final code can be:

$.post('../update.php/?' + queryString, function(data) {
    $('#updatestatus').html(data);
});