0

選択したドロップダウンメニューのフォローアップフィールドを作成しようとしています。

たとえば、最初のドロップダウンメニューには、('yes' => 1、'no' => 2、'nothing' => 3)があります。オプションの1つを選択した後、後で表示されるフィールドを変更したい。たとえば、「はい」を選択した場合、次のフィールドは選択ドロップダウンメニューになります。「いいえ」の場合はテキスト領域になり、「いいえ」の場合は何も表示されません。

自分でいくつかのコードを試しましたが、何かを選択した直後に次のフィールドを更新する方法がわからないため、機能しませんでした。私はこのようなことを試みました:

if (select == 1) {
    echo "$select2";
} else if (select == 2) {
    echo "<input type='text' name='textarea1'/>";
}​

しかし、私はページにフィールドを更新させる方法を知りません...

私を助けてください

ありがとう

4

1 に答える 1

1

アイデアは、前の質問の回答に応じて、JavaScriptを使用して質問を表示/非表示にすることです。これは決定木と呼ばれます。あなたがそれをグーグルすれば、彼らは来るでしょう。あなたはあなたのために大部分の重労働をするたくさんの例とライブラリを見つけることができます。

自分で作成したい場合は、これを非常に単純化した方法で行います。これはスケーラブルなソリューションではありませんが、どのように機能するかについての基本的な考え方を提供するはずです。

HTML

<label>Do you want this?
    <select name="choices" id="choices">
        <option value="1">Yes</option>
        <option value="2">No</option>
        <option value="3" selected>Nothing</option>
    </select>
</label>
<div id="choices-followup">
    <div id="followup1">
        <label>
            How bad do you want this?
            <select>
                <option>Give it to me now!</option>
                <option>Meh...</option>
            </select>
        </label>
    </div>
    <div id="followup2">
        <label>Why not?<br />
            <textarea></textarea>
        </label>
    </div>
</div>​

JavaScript

// Whenever the user changes the value of
// the element with ID "choices", perform
// this function.
$('#choices').on('change', function() {
    
    // Grab the choice value
    var choice = $(this).val();
    
    // Cache the "choices-followup" object.
    // Every time to you call $('anything'), jQuery
    // goes through the entire DOM looking for that
    // object. Prevent this by making the lookup
    // once, and caching the value.
    var choices_followup = $('#choices-followup');
    
    // No matter what the choice, hide all possible
    // follup fields.
    $('div', choices_followup).hide();
    
    // Also, reset their values.
    $('select, textarea, input', choices_followup).val('');
    
    // If this, then that, etc.
    switch(choice) {
        case '1':
            $('#followup1').show();
            break;
        case '2':
            $('#followup2').show();
            break;
    }
});​

CSS

#choices-followup > div { display: none; }​
于 2012-04-15T19:27:24.740 に答える