JQuery, iframes и формы О, МОЙ! - PullRequest
2 голосов
/ 21 мая 2011

Мой первый пост, поэтому, если я что-то не так, прошу прощения.Кроме того, это мой первый раз, когда я широко использую jquery, так что еще раз ... не бейте меня сильно.

Хорошо, вот ситуация ...

У меня есть шаблон WP, которыйдовольно сильно jqueried (не мой), и я не хочу пытаться разрешать какие-либо конфликты в коде, поэтому я создал свои формы, внешние по отношению к WP, включил некоторые jquery, которые требуются для моего клиента, и вставляю их в.

Все шло хорошо, пока я не хотел добавить форму, которая почти аналогична другой форме, которую я имею, но требуемая логика другая.Я назвал формы различными именами и идентификаторами, чтобы они не конфликтовали друг с другом, и вставил их в рамки. Представления в обеих формах работают нормально, и нет никакого конфликта с элементами внутри форм или другими внутренними элементами форм iframed (даже если ониимеют одинаковое имя и идентификатор).Однако jquery, который я написал (noob, пишущий да), запускается только для загруженной ПЕРВОЙ формы (другие формы прекрасно загружаются, поскольку в них нет запроса).Таким образом, я могу перевернуть свои jquery формы, и вуаля, форма, которая была второй, а теперь первой, срабатывает.Однако форма, которая была первой, а теперь второй, не срабатывает.Я попытался изменить имена элементов внутри форм, а также изменить идентификатор формы.

Пожалуйста, имейте это в виду ... формы находятся на своих отдельных страницах, которые затем вставляются вродительская страница, поэтому, насколько я понимаю, формы могут иметь одинаковые имена элементов (которые мне нужны для соответствия удаленному провайдеру).Я называю каждую форму другим именем и идентификаторомКаждая страница формы имеет свой собственный вызов кодов jquery.

Я не уверен, сколько кода вам нужно здесь, и я понимаю, что мой код сейчас может быть беспорядочным, но я просто обеспокоен функциейЯ буду работать над формой и скоростью позже.;)

Часть jquery, которую я вызываю со КАЖДОЙ страницы формы (видя, что это отдельные страницы) (без вызова вызываемых функций)

    $(document).ready(function(){ // jquery equivilant of the onload
    var departure = $("#departure").val(); //this pulls the value from the hidden departure field.
  //var destin = $("#destination").val();
  getDeparture(departure); //runs the get departure function
  getDestination(departure); //runs the get destination function

  $("#gateway_dep").live("change",function(){ //when the destination drop down is changed do the following code
    var departure = $(this).val(); // get the current value of the departure dropbox. Because we explicitly ran this function on the departure drop down, we can use $(this).val() to get the current selection
    getDestination(departure); // when the departure drop down is changed, reload the destinations for that drop down.
     //getDuration(departure, destination);
     //reset duration dropdown if they change the gateway
     //disable the dropdown
     //getRated();
     $("#duration").attr('disabled', 'disabled');
     //set text in dropdown back to original
     $("#duration").clearOptions({placeholderText:'Select Destination First......'});
     //sets the width of the dropdown back to original
     var min_width = 195;
     $('#duration').css('min-width', min_width + 'px');
     //reset the hotel dropdown if they change the gateway
    $("#hotel_no").attr('disabled', 'disabled');
     $("#hotel_no").clearOptions({placeholderText:'Select Destination First......'});
     $('#hotel_no').css('min-width', min_width + 'px');
     //reset ratings
     $("#star").attr('disabled', 'disabled');
     $("#star").clearOptions({placeholderText:'Select Destination First......'});
     $('#star').css('min-width', min_width + 'px');
     //reset prices
     $("#price_max").attr('disabled', 'disabled');
     $("#price_max").clearOptions({placeholderText:'Select Destination First......'});
     $('#price_max').css('min-width', min_width + 'px');
  });

  $("#dest_dep").live("change",function(){ //when the destination drop down is changed do the following code
    var departure = $("#gateway_dep").val();
    var destination = $(this).val(); // get the current value of the destination dropbox. Because we explicitly ran this function on the departure drop down, we can use $(this).val() to get the current selection
    //window.alert(departure);
    //window.alert( $(this).val() );
    getDuration(departure, destination); // when the departure drop down is changed, reload the destinations for that drop down.
    getHotels(departure, destination);
    getRated();
    getPrices();
  });
});

(function($) {

    //plugin definition
    $.fn.clearOptions = function(options) 
    {
        var opts = $.extend({}, $.fn.clearOptions.defaults, options);

        return this.each(function() {
            //Retain the existing placeholder for the dropdown
            if(opts.retainExistingPlaceholder) {
                $(this).children('option:not(:first)').remove();
            }
            else {
                $(this).children('option').remove();
                if(opts.placeholderText != null) {
                    $(this).append('<option value="' + opts.placeholderValue + '">' + opts.placeholderText + '</option>');
                }
            }
        });
    }

    $.fn.clearOptions.defaults = 
    {
        placeholderText: 'Select...',
        placeholderValue: '',
        retainExistingPlaceholder: false
    }; 

})(jQuery);

Теперь у меня есть две формы, которые несколько используют эту логику.

    <form name="lastminute" id="lastminute" method="post" action="http://vas.sax.softvoyage.com/cgi-bin/handler.cgi" target="_blank" onSubmit="return checkform()">
<!--<form name="packages" id="packages" method="post" action="http://function42.biz/custom/postvars.php">-->
<input type="hidden" name="searchtype" value="PA" />
<input type="hidden" name="alias" value="xxx" />
<input type="hidden" name="code_ag" value="xxx" />

<input type="hidden" name="departure" id="departure" value="Toronto" /> <!-- This sets a hidden field up with a default departure city. You can use a PHP var here if you want different ones throughout your site -->
<input type="hidden" name="destination" id="destination" value="All%20Countries" />
<table class="inside_call" width="100%" cellspacing="0" cellpadding="5" border="0"><tr><td class="b2clabeltext">Departure from
:</td>
  <td id="departurediv" ><select name="gateway_dep" id="gateway_dep" disabled="disabled">
    <option>Loading...</option>
  </select></td>
<td class="b2clabeltext">Destination
:</td>
  <td id="destinationdiv"><select name="dest_dep" id="dest_dep" disabled="disabled">
    <option>Select Departure First...</option>
  </select></td></tr><tr>
<td class="b2clabeltext" style="float:left; padding-right:10px;">Date:</td><td id="datediv" class="inside_call" style="padding-bottom:10px;"><?php
$nextweekend = date( 'Ymd', strtotime("next Saturday +7 day")); ?>
<select name="date_dep"><option value="<?php echo $nextweekend; ?>"><?php echo $nextweekend; ?></option> <?php
for($i=0;$i<2;$i++) {
$nextweekend = date( 'Ymd', strtotime($nextweekend . "+7 day"));
?><option value="<?php echo $nextweekend; ?>"><?php echo $nextweekend; ?></option><?php
}
?></select></td>
<td class="b2clabeltext">Duration
:</td>
  <td id="durationdiv"><select name="duration" id="duration" style="width: 195px;" disabled="disabled">
    <option>Select Destination First...</option>
  </select></td></tr><tr>
<td class="b2clabeltext">Hotels:</td>
<td id="hoteldiv"><select name="hotel_no" id="hotel_no" style="width: 195px;" disabled="disabled">
 <option>Select Destination First...</option>
</select></td>
<td class="b2clabeltext">Ratings:</td><td id = "ratediv"><select name="star" id="star" style="width: 195px" disabled="disabled">
    <option>Select Destination First...</option>
  </select></td></tr>
<tr><td class="b2clabeltext">Prices:</td><td id = "pricesdiv"><select name="price_max" id="price_max" style="width: 195px" disabled="disabled">
  <option>Select Destination First...</option>
</select></td>.............yadda yadda yadda down to the submit button

И следующая форма ...

<form name="packages" id="packages"
> method="post"
> action="http://vas.sax.softvoyage.com/cgi-bin/handler.cgi"
> target="_blank" onSubmit="return
> checkform()"> 
> <input type="hidden" name="searchtype"
> value="PA" /> <input type="hidden"
> name="alias" value="xxx" /> <input
> type="hidden" name="code_ag"
> value="xxx" />
> 
> <input type="hidden" name="departure"
> id="departure" value="Toronto" /> <!--
> This sets a hidden field up with a
> default departure city. You can use a
> PHP var here if you want different
> ones throughout your site --> <input
> type="hidden" name="destination"
> id="destination"
> value="All%20Countries" /> <table
> class="inside_call" width="100%"
> cellspacing="0" cellpadding="5"
> border="0"><tr><td
> class="b2clabeltext">Departure from
> :</td>   <td id="departurediv"
> ><select name="gateway_dep" id="gateway_dep" disabled="disabled">
>     <option>Loading...</option>   </select></td> <td
> class="b2clabeltext">Destination
> :</td>   <td
> id="destinationdiv"><select
> name="dest_dep" id="dest_dep"
> disabled="disabled">
>     <option>Select Departure First...</option>  
> </select></td></tr><tr> <td
> class="b2clabeltext"
> style="float:left;
> padding-right:10px;">Date:</td><td
> id="datediv" class="inside_call"
> style="padding-bottom:10px;"><script>DateInput('date_dep',
> true, 'YYYYMMDD')</script></td> <td
> class="b2clabeltext">Duration :</td>  
> <td id="durationdiv"><select
> name="duration" id="duration"
> style="width: 195px;"
> disabled="disabled">
>     <option>Select Destination First...</option>  
> </select></td></tr><tr> <td
> class="b2clabeltext">Hotels:</td> <td
> id="hoteldiv"><select name="hotel_no"
> id="hotel_no" style="width: 195px;"
> disabled="disabled">  <option>Select
> Destination First...</option>
> </select></td> <td
> class="b2clabeltext">Ratings:</td><td
> id = "ratediv"><select name="star"
> id="star" style="width: 195px"
> disabled="disabled">
>     <option>Select Destination First...</option>  
> </select></td></tr> <tr><td
> class="b2clabeltext">Prices:</td><td
> id = "pricesdiv"><select
> name="price_max" id="price_max"
> style="width: 195px"
> disabled="disabled">   <option>Select
> Destination First...</option>
> </select></td>...yadda yadda yadda
> down to the submit button

В настоящее время для обеих форм отправления запрашиваются через dbПозвоните, затем запрашиваются пункты назначения в зависимости от отправления, затем запрашиваются отели в зависимости от пункта назначения, а продолжительность запрашивается в зависимости от назначения ... очень разветвленно и у меня болит мозг на недели LOL.Но я надеюсь, что это помогает увидеть мою делика ...

Я ТОЛЬКО использую jquery для загрузки данных в формы и разрешаю формам обрабатывать отправку.Я надеюсь, что мне не нужно помещать формы на отдельных страницах, и это помогает консолидировать вещи для моего клиента.Я думал, что ответом будет iframing.

Я ищу какой-то свежий взгляд на это.Спасибо.

Ответы [ 2 ]

2 голосов
/ 21 мая 2011

Прекращено чтение в "(даже если они имеют одинаковое имя и идентификатор)."

Два элемента на одной странице не могут иметь одинаковый идентификатор.

0 голосов
/ 21 мая 2011

Вы делаете один и тот же код снова и снова.И это очень плохо.

Вы должны сделать что-то вроде:

array = ["hotel_no","start","price_max"];
for each element of array do
     $("#"+element).attr('disabled', 'disabled')
           .clearOptions({placeholderText:'Select Destination First......'})
           .css('min-width', min_width + 'px');

Это только первое, что вы должны были сделать

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...