I am working on a page where I show different input fields, depending on the selection that a user did.
Example 1:
<input type="text" name="color" value="" id="5">
<input type="text" name="location" value="" id="6">
<input type="text" name="age" value="" id="7">
Example 2:
<input type="text" name="color" value="" id="5">
<input type="text" name="destination" value="" id="8">
<input type="text" name="hours" value="" id="9">
<input type="text" name="date" value="" id="10">
Question 1: How can I get all input fields with jQuery when the input fields itself are dynamic?
Question 2: On the serverside, I want to process the input fields with their value and ID. How can I make this dynamic?
I know that this can be done easily when everything is fix, e.g.:
var color = $('#color').val();
var destination = $("#destination").val();
var dataString = 'color=' + color + "&destination=" + destination;
$.ajax({
type: "GET",
url: "do_something.php",
data: dataString,
async: false,
success: function(data){
console.log('success');
}
});
You can use .serialize()
to create your data-string. It will dynamically grab all the data for the form and turn it into a string like you're attempting to build:
$.ajax({
type: "GET",
url: "do_something.php",
data: $("form").serialize(),
async: false,
success: function(data){
console.log('success');
}
});
Docs for .serialize()
: http://api.jquery.com/serialize
Note, you may need to refine the $("form")
selection to be more specific if you have more than one form in the DOM.
As for your second question, you should generally keep questions on SO to one question per post. That being said, you should set the ID
attribute to the value
attribute instead, that way it will be passed to the PHP script when the form is submitted, ID
will be lost since it's not transmitted with the form.
If I understand well your first question is that you want get the values and the id's of the dinamic inputs with jquery. Yo can do that, inserting the dinamic inputs allways in the same div and simply do something like:
var data = new Array();
$("#id-div input").each(function() {
data.push({id: $(this).attr("id"), value: $(this).attr("value")});
});