5

Ok, I've been looking and looking for about 2 weeks now and I've yet to find exactly what I need to figure out, so now is the time to ask the experts!

I'm working on an advertising management system and one of the parts of the request form is to select start and end dates for an ad. The user is given an option of adding more dates.

So, there are two inputs that are there initally...

<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">

Then, under that is an option to dynamically add more inputs. When the user adds more inputs, it just copies those initial inputs, so we end up with more instances. For example:

<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">

<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">

Is there a way to send the results of these inputs as an array using .load()? I have it sending and displaying the info for one set of inputs with the code below...

var startDate = $("#startDateInput").val();
var endDate = $("#endDateInput").val(); 
$("#adBooking").show().load('../scripts/checkSpots.php', { startDate: startDate, endDate: endDate});

I guess I just don't 100% understand how to do this. I've been racking my brain for the past two weeks but I can't find anything totally relevant to what I'm doing.

But, what I need to do is make an array of data out of all the startDate and endDate inputs and then throw it through the .load() and into the checkSpots.php page and have it display the information for each set of start/end dates.

Is there a different way of doing this? Maybe a more efficient way? Or, if anyone can shed a bit of light on this broken jQuery noob, I'd greatly apprecaite it! :D

5 Answers 5

2
$(function() {
    $("#add-date").click(function(e) {
        var i = $('.end-date').length + 1;
        $('<p class="dates">' + 
          '<input class="start-date" name="startDate[' + i + ']" id="startDate' + i + '" />' + 
          '<input class="end-date" name="endDate[' + i + ']" id="endDate' + i + '" />' + 
          '</p>').insertAfter('.dates:last');
          e.preventDefault();
    });
    $('#my-form').submit(function() {
        var post_data = $(this).serialize();
        //$("#adBooking").show().load('../scripts/checkSpots.php', post_data);
        alert(post_data);
        return false;
    });

PHP

<?php
   foreach($_POST['startDate'] as $key => $val ) {
         echo $key;  // 1
         echo $val; // 07/12/2011
    }
   foreach($_POST['endDate'] as $key => $val ) {
         echo $key;  // 1
         echo $val; // 09/12/2011
    }
?>
3
  • 1
    I think this answer is better than mine -- definitely more thorough and I love the .serialize() on the form. Never thought to do that! Commented Dec 7, 2011 at 20:06
  • This is exactly what I needed. Thank you! You guys are sanity-savers! Much appreciated Commented Dec 8, 2011 at 12:48
  • @Adam West: hi dude, if this answer helped or solved your question, can you tick the check? thank's Commented Dec 8, 2011 at 13:09
1

First things first, ID's need to be unique, so when a new date pair is added, append a qualifier on the end of the id:

<input type="text" name="startDate[]" id="startDateInput1">
<input type="text" name="enddate[]" id="endDateInput1">

<input type="text" name="startDate[]" id="startDateInput2">
<input type="text" name="enddate[]" id="endDateInput2">

Or better yet, use a class:

<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">

<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">

Then you can apply some jQuery voodoo whenever you'd like (button click, submit, etc):

$('#myButton').click(function(){

    // Our ajax post data. For example, $_POST['startDates'][2] would 
    // give you the 3rd start date in your php file.
    var data = {
        startDates: new Array(),
        endDates: new Array()
    };

    // Loop through each date pair, extract its value, and add it to our post data
    $('.startDateInput').each(function(){
        data.startDates.push(this.val());
    });
    $('.endDateInput').each(function(){
        data.endDates.push(this.val());
    });

    // Load it!
    $('#result').load('doSomething.php', data);

});

Note: Above code is not tested, just an example of one possible solution.

Hope that helps. Oh, and obligatory Family Guy reference.

1
  • Haha, I get the Family Guy/Batman references all the time. I enjoy the Mayor one's better! Thanks for the help! I used a mish-mash of the answers and came out with exactly what I need. Thanks a lot for all the help! Much Appreciated! Commented Dec 8, 2011 at 12:44
0

There is a major flaw in your logic: Any id attribute must be unique in the document. As you use several id's more than once, it will not work or give unexpected results at best.

1
  • In trying to create a non-muddled version of my question, I forgot to include that I was adding the count # to the ID's making them 'startDateInput1','startDateIpnut2' and so forth. Thanks for the observation! Commented Dec 8, 2011 at 12:52
0

First, you shouldn't use the same id on multiple elements within a single html page. That's going to cause all sorts of unpredictable behavior. Use class instead so:

<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">

<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">

Then you need to query for all the input elements using jquery loop through each element and assign its value to the appropriate array.

var myEndDateArray = [], myStartDateArray = [];
$(".endDateInput").each(function() {
     myEndDateArray.push($(this).val())

});
$(".startDateInput").each(function() {
     myStartDateArray.push($(this).val())

});

Finally, you must post the array data to your page in a compatible post format.

$("#adBooking").show().load('../scripts/checkSpots.php', { 'startdate[]': myStartDateArray, 'enddate[]': myEndDateArray});
0

I bumped int this problem lately, and I found aSeptik solution is very useful.

But there is a mistake in it. From jQuery documentation:

Request Method

The POST method is used if data is provided as an object; otherwise, GET is assumed.

Since the result of the .serialze() function is string the .load() methode will use GET.

JS code (same):

$(function() {
    $("#add-date").click(function(e) {
        var i = $('.end-date').length + 1;
        $('<p class="dates">' + 
          '<input class="start-date" name="startDate[' + i + ']" id="startDate' + i + '" />' + 
          '<input class="end-date" name="endDate[' + i + ']" id="endDate' + i + '" />' + 
          '</p>').insertAfter('.dates:last');
          e.preventDefault();
    });
    $('#my-form').submit(function() {
        var post_data = $(this).serialize();
        //$("#adBooking").show().load('../scripts/checkSpots.php', post_data);
        alert(post_data);
        return false;
    });

PHP script with _GET:

<?php
   foreach($_GET['startDate'] as $key => $val ) {
         echo $key;  // 1
         echo $val; // 07/12/2011
    }
   foreach($_GET['endDate'] as $key => $val ) {
         echo $key;  // 1
         echo $val; // 09/12/2011
    }
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.