drupal 7 FAPI-ajax更改事件不与textfield一起使用

时间:2012-10-30 05:49:53

标签: jquery drupal drupal-7 drupal-modules drupal-fapi

如何使用ajax change事件实时获取和显示textfield的值(即显示每个值更改的新值)。我尝试了以下内容,但似乎#ajax['event']='change'无法使用textfield。 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模块的浏览器中显示回来???

1 个答案:

答案 0 :(得分: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;
}

希望这能解决你的问题......穆罕默德。