1

テキストフィールドの値をリアルタイムで取得して表示するために ajax 変更イベントをどのように使用しますか (つまり、値が変更されるたびに新しい値が表示されます)。次のことを試しましたが#ajax['event']='change'、テキストフィールドでは機能していないようです。Ajax 呼び出しは、テキスト フィールドがフォーカスを失った場合にのみトリガーされます。たとえば、テキスト フィールドに Hello を書き込むと、テキスト フィールドの外側をクリックするまで表示されません。これが私のコードです:-

function test1_form($form, &$form_state)
{
   $form['text']=array(
         '#title'=>'Text:',
         '#type'=> 'textfield',
         '#ajax'=> array(
            'event'=>'change',
            'callback'=>'test1_form_submit',
            'wrapper'=>'contnr',
            'method'=>'replace',
        ),
    );

   $form['up_button']=array(
      '#title'=>t('Preview:'),
      '#type'=>'markup',
      '#prefix'=>'<div id="contnr">',
      '#suffix'=>'</div>',
      '#markup'=>'<h2>This is to be replaced</h2>',
   );
   return $form;
}

function test1_form_submit($form, $form_state)
{       
  return $form_state['values']['text'];
}

テキストフィールドの値をリアルタイムで取得し、drupal 7 モジュールのブラウザーに表示する方法はありますか?

4

1 に答える 1

1

jQueryのkeydown()イベントを使用して同じ結果を得ることができます。

コードサンプル:

jQuery("#textFieldID").keydown(function(e) {
    jQuery("#contnr").html("<h2>" + jQuery(this).val() + "</h2>");

    // the above line can be broken into 2 lines as follows:
    var myVal = jQuery(this).val(); // grab the textfield value
    jQuery("#contnr").html("<h2>" + myVal + "</h2>"); // set the value to the div
});

アップデート:

jsコードを.jsファイルにコピーして(呼び出してmy-script.jsモジュールのディレクトリに配置)、次のように#attachedプロパティを使用してjavascriptファイルをページに追加できます。

function test1_form($form, &$form_state)
{
   $form['text']=array(
         '#title'=>'Text:',
         '#type'=> 'textfield',
         '#ajax'=> array(
            'event'=>'change',
            'callback'=>'test1_form_submit',
            'wrapper'=>'contnr',
            'method'=>'replace',
        ),
    );

   $form['up_button']=array(
      '#title'=>t('Preview:'),
      '#type'=>'markup',
      '#prefix'=>'<div id="contnr">',
      '#suffix'=>'</div>',
      '#markup'=>'<h2>This is to be replaced</h2>',
   );

   // the only code you need to add.
   $form['#attached']['js'] = array(
       drupal_get_path('module', 'test1') . '/my-script.js',
   );

   return $form;
}

これがあなたの問題を解決することを願っています...ムハンマド。

于 2012-10-30T07:20:55.217 に答える