0

$location変数は、Codeigniter を使用してセッションを使用して定義されます。「Austin」、「Houston」などです。各場所は異なるツアーを提供しています。$location変数は既に定義されているので、特定の場所で利用可能なツアーをドロップダウン ボックスに入力するだけです。ドロップダウンはフォームの一部であり、特定のコントローラーで検証されます。コードの空白を埋める Javascript の例を教えてください。

   <?php
$location = $this->session->userdata('location');

// javascript goes here to decide which location and what tours to send in an array.
// $options_tour will be the returned array sent to the form_dropdown()

//form ...
$data_tour = 'class="span12"';
$tour = array('style' => 'font-weight:bold;');
echo form_label('Select Tour: ','tour', $tour);
echo form_dropdown('tour', $options_tour, '', $data_tour);
    ?>
 
4

1 に答える 1

0

このように JavaScript を使用してフォームにデータを入力するには、多少回りくどい方法が必要になります。

$location 変数の値を取得するために JavaScript が読み取る隠しフィールドを作成するか、それを取得する ajax 呼び出しを作成します。

次に、場所に基づいて適切な値を返す JavaScript 関数を作成します。何かのようなもの:

function get_tours( location ){

    var tours = {};

    switch locations {

        case 'Austin':
         tours = { "City Center": { 
                                   "text": "City Center" 
                                   "value": "city_center"
                                  }
                 };
        break;

        //etc...
    }

    return tours;
}

AJAX メソッドを使用することを選択した場合は、AJAX が成功したときに、このツアー オプション設定関数を呼び出す必要があります。

JavaScript 変数にツアーが含まれているので、PHP によって生成されたページ内の要素の要素を更新する必要があります。何かのようなもの:

function create_tour_options ( tours ){

    var select = document.getElementById('tour');

    for ( tour in tours ){
        tour_option = document.createElement('option');
        tour_option.value = tours['tour']['value'];
        tour_option.text = tours['tour']['text'];
        select.appendChild('tour_option');
    }

    // Probably more efficient to create a new select object 
    // and replace the existing one instead of adding and 
    // removing individual options. 
}

さらに、JavaScript を使用する必要がない場合は、単純に php 関数を記述して上記を実行し、$options_tour 変数を返すことができます。何かのようなもの:

function get_tours( $location='Austin' ){

    $tours = array();

    switch $location {

        case 'Austin':
            $tours = array( "text" => "City Center" 
                            "value" => "city_center"
                          );
        break;

        //etc...
    }

    return $tours;
}

オプションは最初のページの読み込み時に生成され、後で挿入する必要がないため、可能であれば PHP を使用する方がよいと思います。

また、JQuery を使用しているかどうかわからないので、標準の JavaScript サンプル コードを使用してみました。

于 2013-03-28T21:21:33.363 に答える