我正在尝试使用JavaScript和Drupal表单。目前,我正在尝试以模块的管理形式创建一个按钮,该模块将使用JavaScript将选项附加到选择列表中。我遇到的问题是,当我单击按钮时,我的JavaScript会被调用,但整个表单会刷新。我查看了Forms API参考,认为可以在按钮上设置某种属性来阻止它,但是什么也没找到。有什么办法可以阻止按钮刷新页面,或者这是死路一条?
$form['#attached']['js'] = array(
drupal_get_path('module', 'test').'/js/test.js',
);
$form['list'] = array(
'#type' => 'select',
'#options' => array(),
'#attributes' => array(
'name' => 'sellist',
),
'#size' => 4,
);
$form['add_button'] = array(
'#type' => 'button',
'#value' => 'Add',
'#attributes' => array(
'onclick' => "add_to_list(this.form.sellist, 'Append' + this.form.sellist.length);",
),
);
//JavaScript
function add_to_list(list, text) {
try {
list.add(new Option(text, list.length), null) //add new option to end of "sample"
}
catch(e) {
list.add(new Option(text, list.length));
}
}
我的最终代码:
<?php
function jstest_menu() {
$items['admin/config/content/jstest'] = array(
'title' => 'JavaScript Test',
'description' => 'Configuration for Administration Test',
'page callback' => 'drupal_get_form',
'page arguments' => array('_jstest_form'),
'access arguments' => array('access administration pages'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function _jstest_form($form, &$form_state) {
$form['list'] = array(
'#type' => 'select',
'#options' => array(),
'#size' => 4,
);
$form['text'] = array(
'#type' => 'textfield',
);
$form['add_button'] = array (
'#type' => 'button',
'#value' => t("Add"),
'#after_build' => array('_jstest_after_build'),
);
return $form;
}
function _jstest_after_build($form, &$form_state) {
drupal_add_js(drupal_get_path('module', 'jstest').'/js/jstest.js');
return $form;
}
JavaScript
(function ($) {
Drupal.behaviors.snmpModule = {
attach: function (context, settings) {
$('#edit-add-button', context).click(function () {
var list = document.getElementById('edit-list');
var text = document.getElementById('edit-text');
if (text.value != '')
{
try {
list.add(new Option(text.value, list.length), null);
}
catch(e) {
list.add(new Option(text.value, list.length));
}
text.value = '';
}
return false;
});
$('#edit-list', context).click(function () {
var list = document.getElementById('edit-list');
if (list.selectedIndex != -1)
list.remove(list.selectedIndex);
return false;
});
}
};
}(jQuery));