Reputation: 3696
A few days ago I posted this question: switch statement and loops using jquery/javascript
which ended up with me creating a series of divs using this code
for (var i = 1; i <= $("#play option:selected").text(); ++i) {
$("#play_"+i).slideDown().find("input").addClass("someClass");
}
My problem is that I now need to get the value of each #play
div and send that to a php script via ajax.
If I had a set number of divs I could do that easily, but how do I do it when I don't know how many #play there will be?
FURTHER DESCRIPTION!
It seems I didn't explain myself clearly in my original question so I will try and explain things better.
I want to make an AJAX call to a remote php script using the $.pos
t jQuery method. I can send information the remote script needs very easily. Here is an example:
$("#submit").click(function() {
$.post("../includes/process.php",
{
play_0: $("#play\_0").val(),
play_1: $("#play\_1").val(),
play_2: $("#play\_2").val(),
play_3: $("#play\_3").val(),
play_4: $("#play\_4").val()
},
function(data) {
$("#activityWindow").empty().append(data);
});
});
The php script can now access this information through the $_POST array - just like a normal form submission.
If I have generated divs (#play_) using a loop, I can't hard code the $.post
method in the way I have above. Really I need to include a loop in the syntax somewhere - I just can't work out how to do it! I hope this has made things clearer.
Upvotes: 1
Views: 283
Reputation: 82513
jQuery has a attribute startsWith selector, then you can easily loop through them to create your object...
// Create an empty object
var data = {};
// Get all <div> elements that have an id attribute that starts with "play_"
var divs = $("div[id^=play_]");
// Loop through the <div> elements, using jQuery's each function
divs.each(function() {
// Get the current div we are looping with jQuery
var div = $(this);
// Get the ID of the current div
var id = div.attr("id");
// Get the value of the current div
var val = div.html();
// Object properties can be set dynamically like this in Javascript
data[id] = val;
});
// Loop is done, all properties have been set
alert(data.play_0);
Upvotes: 3
Reputation: 2821
Could you use the class in your selector like $("div.someClass").each(function() {
This would only work if these are the only divs to use that class. If that's not the case you could just add another class to them.
Inside the function you could add the value to an array.
Edit: It would be better to use the "div[id^=play_]"
selector. If you want to grab the value from the input and put it in an array you could say:
$("div[id^=play_] input").each(function() {
valueArray.push($(this).val());
});
Upvotes: 0