tebrown tebrown - 6 months ago 15
Javascript Question

Two forms interacting with each other

I have two identical forms that are on separate pages.

Page 1

The form on this page is a quick call to action so to speak that will pre populate the form on the next page.

<form action="/xxxx" method="post">
<select id="island" name="island">
<option selected value="base">Select an Island</option>
<option value="north-island">North Island</option>
<option value="south-island">South Island</option>
</select>
</form>


Page 2

As it stands, I can populate the form below using the following:

<select id="island" name="island">
<optio value="base">Select an Island</option>
<option <?php if( isset($_POST['island']) ) { echo 'selected'; } ?> value="north-island">North Island</option>
<option <?php if( isset($_POST['island']) ) { echo 'selected'; } ?> value="south-island">South Island</option>
</select>


Now, my problem I have is that I am using AJAX to retrieve data which works fine if I use the form as it is on Page 2 but going from page 1 to page 2 it doesn't pick up the .change and therefor the results don't show.

$('#island').change(function() {

var selectedValue = $(this).find(':selected').val();

jQuery.ajax({
type: 'POST',
data: {
action: 'cfd_map',
option: selectedValue
},
url: "xxxxxx",
success: function(data) {
$('.results').html(data).fadeIn('slow');
}
});
});


Anyone help me out here?

Cheers

Answer

If results only need to be available going from page 1 to page 2 and not going back to page 1 from page 2 then following will work:

$('#island').change(function() {

  var selectedValue = $(this).val();
  // only do ajax if there is a value
  if (selectedValue) {
    jQuery.ajax({
      type: 'POST',
      data: {
        action: 'cfd_map',
        option: selectedValue
      },
      url: "xxxxxx",
      success: function(data) {
        $('.results').html(data).fadeIn('slow');
      }
    });
  }
  // now trigger change 
}).change();

It simply triggers the change after the handler is declared. Triggering the change will then make the ajax call to get results

Since the server already sets value on page 2 there should be no other local storage needed - unless this needs to work both ways