Functions for Drupal's Ajax framework.
Drupal's Ajax framework is used to dynamically update parts of a page's HTML based on data from the server. Upon a specified event, such as a button click, a callback function is triggered which performs server-side logic and may return updated markup, which is then replaced on-the-fly with no page refresh necessary.
This framework creates a PHP macro language that allows the server to instruct JavaScript to perform actions on the client browser. When using forms, it can be used with the #ajax property. The #ajax property can be used to bind events to the Ajax framework. By default, #ajax uses 'system/ajax' as its path for submission and thus calls ajax_form_callback() and a defined #ajax['callback'] function. However, you may optionally specify a different path to request or a different callback function to invoke, which can return updated HTML or can also return a richer set of Ajax framework commands.
Standard form handling is as follows:
- A form element has a #ajax property that includes #ajax['callback'] and omits #ajax['path']. See below about using #ajax['path'] to implement advanced use-cases that require something other than standard form handling.
- On the specified element, Ajax processing is triggered by a change to that element.
- The browser submits an HTTP POST request to the 'system/ajax' Drupal path.
- The menu page callback for 'system/ajax', ajax_form_callback(), calls drupal_process_form() to process the form submission and rebuild the form if necessary. The form is processed in much the same way as if it were submitted without Ajax, with the same #process functions and validation and submission handlers called in either case, making it easy to create Ajax-enabled forms that degrade gracefully when JavaScript is disabled.
- After form processing is complete, ajax_form_callback() calls the function named by #ajax['callback'], which returns the form element that has been updated and needs to be returned to the browser, or alternatively, an array of custom Ajax commands.
- The page delivery callback for 'system/ajax', ajax_deliver(), renders the element returned by #ajax['callback'], and returns the JSON string created by ajax_render() to the browser.
- The browser unserializes the returned JSON string into an array of command objects and executes each command, resulting in the old page content within and including the HTML element specified by #ajax['wrapper'] being replaced by the new content returned by #ajax['callback'], using a JavaScript animation effect specified by #ajax['effect'].
A simple example of basic Ajax use from the Examples module follows:
function main_page() {
return drupal_get_form('ajax_example_simplest');
}
function ajax_example_simplest($form, &$form_state) {
$form = array();
$form['changethis'] = array(
'#type' => 'select',
'#options' => array(
'one' => 'one',
'two' => 'two',
'three' => 'three',
),
'#ajax' => array(
'callback' => 'ajax_example_simplest_callback',
'wrapper' => 'replace_textfield_div',
),
);
// This entire form element will be replaced with an updated value.
$form['replace_textfield'] = array(
'#type' => 'textfield',
'#title' => t("The default value will be changed"),
'#description' => t("Say something about why you chose") . "'" .
(!empty($form_state['values']['changethis'])
? $form_state['values']['changethis'] : t("Not changed yet")) . "'",
'#prefix' => '<div id="replace_textfield_div">',
'#suffix' => '</div>',
);
return $form;
}
function ajax_example_simplest_callback($form, $form_state) {
// The form has already been submitted and updated. We can return the replaced
// item as it is.
return $form['replace_textfield'];
}
In the above example, the 'changethis' element is Ajax-enabled. The default #ajax['event'] is 'change', so when the 'changethis' element changes, an Ajax call is made. The form is submitted and reprocessed, and then the callback is called. In this case, the form has been automatically built changing $form['replace_textfield']['#description'], so the callback just returns that part of the form.
To implement Ajax handling in a form, add '#ajax' to the form definition of a field. That field will trigger an Ajax event when it is clicked (or changed, depending on the kind of field). #ajax supports the following parameters (either 'path' or 'callback' is required at least):
- #ajax['callback']: The callback to invoke to handle the server side of the Ajax event, which will receive a $form and $form_state as arguments, and returns a renderable array (most often a form or form fragment), an HTML string, or an array of Ajax commands. If returning a renderable array or a string, the value will replace the original element named in #ajax['wrapper'], and theme_status_messages() will be prepended to that element. (If the status messages are not wanted, return an array of Ajax commands instead.) #ajax['wrapper']. If an array of Ajax commands is returned, it will be executed by the calling code.
- #ajax['path']: The menu path to use for the request. This is often omitted and the default is used. This path should map to a menu page callback that returns data using ajax_render(). Defaults to 'system/ajax', which invokes ajax_form_callback(), eventually calling the function named in #ajax['callback']. If you use a custom path, you must set up the menu entry and handle the entire callback in your own code.
- #ajax['wrapper']: The CSS ID of the area to be replaced by the content returned by the #ajax['callback'] function. The content returned from the callback will replace the entire element named by #ajax['wrapper']. The wrapper is usually created using #prefix and #suffix properties in the form. Note that this is the wrapper ID, not a CSS selector. So to replace the element referred to by the CSS selector #some-selector on the page, use #ajax['wrapper'] = 'some-selector', not '#some-selector'.
- #ajax['effect']: The jQuery effect to use when placing the new HTML. Defaults to no effect. Valid options are 'none', 'slide', or 'fade'.
- #ajax['speed']: The effect speed to use. Defaults to 'slow'. May be 'slow', 'fast' or a number in milliseconds which represents the length of time the effect should run.
- #ajax['event']: The JavaScript event to respond to. This is normally selected automatically for the type of form widget being used, and is only needed if you need to override the default behavior.
- #ajax['prevent']: A JavaScript event to prevent when 'event' is triggered. Defaults to 'click' for #ajax on #type 'submit', 'button', and 'image_button'. Multiple events may be specified separated by spaces. For example, when binding #ajax behaviors to form buttons, pressing the ENTER key within a textfield triggers the 'click' event of the form's first submit button. Triggering Ajax in this situation leads to problems, like breaking autocomplete textfields. Because of that, Ajax behaviors are bound to the 'mousedown' event on form buttons by default. However, binding to 'mousedown' rather than 'click' means that it is possible to trigger a click by pressing the mouse, holding the mouse button down until the Ajax request is complete and the button is re-enabled, and then releasing the mouse button. For this case, 'prevent' can be set to 'click', so an additional event handler is bound to prevent such a click from triggering a non-Ajax form submission. This also prevents a textfield's ENTER press triggering a button's non-Ajax form submission behavior.
- #ajax['method']: The jQuery method to use to place the new HTML. Defaults to 'replaceWith'. May be: 'replaceWith', 'append', 'prepend', 'before', 'after', or 'html'. See the jQuery manipulators documentation for more information on these methods.
- #ajax['progress']: Choose either a throbber or progress bar that is displayed while awaiting a response from the callback, and add an optional message. Possible keys: 'type', 'message', 'url', 'interval'. More information is available in the Form API Reference
In addition to using Form API for doing in-form modification, Ajax may be enabled by adding classes to buttons and links. By adding the 'use-ajax' class to a link, the link will be loaded via an Ajax call. When using this method, the href of the link can contain '/nojs/' as part of the path. When the Ajax framework makes the request, it will convert this to '/ajax/'. The server is then able to easily tell if this request was made through an actual Ajax request or in a degraded state, and respond appropriately.
Similarly, submit buttons can be given the class 'use-ajax-submit'. The form will then be submitted via Ajax to the path specified in the #action. Like the ajax-submit class above, this path will have '/nojs/' replaced with '/ajax/' so that the submit handler can tell if the form was submitted in a degraded state or not.
When responding to Ajax requests, the server should do what it needs to do for that request, then create a commands array. This commands array will be converted to a JSON object and returned to the client, which will then iterate over the array and process it like a macro language.
Each command item is an associative array which will be converted to a command object on the JavaScript side. $command_item['command'] is the type of command, e.g. 'alert' or 'replace', and will correspond to a method in the Drupal.ajax[command] space. The command array may contain any other data that the command needs to process, e.g. 'method', 'selector', 'settings', etc.
Commands are usually created with a couple of helper functions, so they look like this:
$commands = array();
// Replace the content of '#object-1' on the page with 'some html here'.
$commands[] = ajax_command_replace('#object-1', 'some html here');
// Add a visual "changed" marker to the '#object-1' element.
$commands[] = ajax_command_changed('#object-1');
// Menu 'page callback' and #ajax['callback'] functions are supposed to
// return render arrays. If returning an Ajax commands array, it must be
// encapsulated in a render array structure.
return array('#type' => 'ajax', '#commands' => $commands);
When returning an Ajax command array, it is often useful to have status messages rendered along with other tasks in the command array. In that case the the Ajax commands array may be constructed like this:
$commands = array();
$commands[] = ajax_command_replace(NULL, $output);
$commands[] = ajax_command_prepend(NULL, theme('status_messages'));
return array('#type' => 'ajax', '#commands' => $commands);
Functions
|
Name |
Location | Description |
|---|---|---|
| ajax_base_page_theme |
includes/ |
Theme callback for Ajax requests. |
| ajax_deliver |
includes/ |
Packages and sends the result of a page callback as an Ajax response. |
| ajax_footer |
includes/ |
Performs end-of-Ajax-request tasks. |
| ajax_form_callback |
includes/ |
Menu callback; handles Ajax requests for the #ajax Form API property. |
| ajax_get_form |
includes/ |
Gets a form submitted via #ajax during an Ajax callback. |
| ajax_prepare_response |
includes/ |
Converts the return value of a page callback into an Ajax commands array. |
| ajax_pre_render_element |
includes/ |
Adds Ajax information about an element to communicate with JavaScript. |
| ajax_process_form |
includes/ |
Form element processing handler for the #ajax form property. |
| ajax_render |
includes/ |
Renders a commands array into JSON. |
File
- includes/
ajax.inc, line 8 - Functions for use with Drupal's Ajax framework.
Comments
Include ajax.inc manually if not on a form
PermalinkIf you want to use the "use-ajax" or "use-ajax-submit" functionality, outside of a form context, you need to include the javascript files yourself.
Add the following code to include the needed code. (Add it to just the needed pages, or set them to load on every page)
drupal_add_library('system', 'drupal.ajax');drupal_add_library('system', 'jquery.form');
You can also attach it to a
PermalinkYou can also attach it to a render element:
<?php$element['#attached'] = array(
'library' => array(
array('system', 'drupal.ajax'),
),
);
?>
AJAX on a link with no form.
PermalinkHere's a simple example of all kinds of AJAXy goodness without a form:
<?php
$link = array(
'#type' => 'link',
'#title' => t('something'),
'#href' => 'some/path',
'#ajax' => array(
'callback' => 'some_callback_function',
'wrapper' => 'ajax-response-goes-here',
'method' => 'replace',
'effect' => 'fade',
),
// Using the onload below is entirely optional; It's just included as
// a reminder of an easy way to add extra simple jQuery tricks.
'#attributes' => array(
'onload' => "jQuery('something-to-hide').hide();",
),
);
$output = "<div id='ajax-response-goes-here'></div>Some HTML and stuff" . drupal_render($link);
?>
Yes, it's better to use the fancy new RenderAPI's renderable array's when you can, but this can make for an easy way to add AJAX to legacy code.
Trigger AJAX with enter key
PermalinkThis isn't documented here, but to trigger an AJAX callback using the enter key when focusing on an element, add keypress = TRUE to the #ajax array, e.g.:
<?php$form['element'] = array(
'#type' => 'textfield',
'#title' => 'Title',
'#ajax' => array(
'callback' => '...',
'keypress' => TRUE,
),
);
?>
#ajax triggers on mousedown
PermalinkMy form is being submitted on press of Enter Key,
but issue is, its even submitting on mouse down on outside textArea
How to avoid submit a form on MouseDown?
even i have tried with below script,
'prevent' =>'mousedown',
or
'prevent' =>'click'
on Submit button
<?php$form = array('body' => array(
'#type' => 'text_format',
'#rows' => 1,
'#after_build' => array('custom_messages_check_format_access'),
'#ajax' => array(
'callback' => '...',
'wrapper' => '..',
'effect' => 'fade',
'method' => 'replace',
'keypress' => TRUE,
),
'#executes_submit_callback' => TRUE,
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Send message'),
'#ajax' => array(
'callback' => '...',
'wrapper' => '..',
'effect' => 'fade',
'method' => 'replace',
'prevent' => 'mousedown',
),
);
?>
please suggest me if am wrong or if i have missed any thing
AJAX with multi field
PermalinkRefering to http://stackoverflow.com/questions/6088455/pass-arguments-to-ajax-callba..., I thought this code could be useful for those who needs to use ajax with a list of fields (ex. products list):
<?php
function multifield_form($form, &$form_state) {
$form = array();
for(
$i = 0; $i < 10; $i++) {$form['row' . $i] = array(
'#title' => t('Row: ' . $i),
'#type' => 'select',
'#options' => array(0, 1, 2),
'#ajax' => array(
'callback' => 'ajax_multifield_callback',
'wrapper' => 'replace_row_div' . $i,
),
);
$form['replace_row' . $i] = array('#type' => 'textfield',
'#title' => t("Result row:" . $i),
// The prefix/suffix provide the div that we're replacing, named by
// #ajax['wrapper'] above.
'#prefix' => '<div id="replace_row_div' . $i . '">',
'#suffix' => '</div>',
);
if (!empty(
$form_state['values']['row' . $i])) {$form['replace_row' . $i]['#value'] = $form_state['values']['row' . $i];
}
}
return $form;
}
function
ajax_multifield_callback($form, $form_state) {// Get field name
$fieldname = $form_state['triggering_element']['#name'];
// The form has already been submitted and updated. We can return the replaced
// item as it is.
return $form['replace_' . $fieldname];
}
?>
Cheers
This seems really confusing.
PermalinkMaybe this link helps: http://browse-tutorials.com/tutorial/create-ajax-forms-drupal-7
You should do bussiness logic
PermalinkYou should do bussiness logic in the form constructor.
See the attached file at:
www.monchacos.com/monchacos/code/creating-forms-template-file-ajax-included
Thank you !
PermalinkThank you for that $form_state['triggering_element']['#name'], I was banging my head for an hour, and then saw your comment. Very appreciated, and works like a charm ;)
Use #parents for that
PermalinkActually, a better way often to use $form_state['triggering_element']['#parents'].
In an AJAX callback, the $form_state['triggering_element'] array contains all the information about the form element that triggered the AJAX action. These include the expected #type and #default_value fields and all the fields filled in by the Form API by default, but it also includes the #name, #parents, and #array_parents fields. These last three can be used to determine what element of a form triggered the action.
The #name field might work for simple forms. It has the name of the element, as a string. In a complex form, though, it might be difficult to work with, as it can be something like '#name' => 'packages[11][pkg_type]'. You'd have to parse that.
The #parents or #array_parents fields are much easier to work with. They each contain an array listing the form elements containing the activating element (including itself). So, you can get something like '#parents' => array('packages', 11, 'pkg_type'), so $form_state['triggering_element']['#parents'][1] will give 11, which is the index of the subform in this example.
Here's some working code. The dpm() call requires the Devel module, and allows you to look at everything in $form_state while you're figuring this out. Remove it when you're done debugging.
<?phpfunction uc_stamps_shipment_edit_update_package($form, $form_state) {
dpm($form_state, 'AJAX $form_state');
$package_id = $form_state['triggering_element']['#parents'][1];
return $form['packages'][$package_id];
}
?>
Be careful. #parents and #array_parents are not always the same (depending on #tree). See the Form API Reference for details, and use dpm() to double-check that they are what you expect.
Thanks for $form_state['triggering_element']['#name']
PermalinkI was searching for days and then I follow your post from stack-overflow and ultimately it solves my problem.
Drupal insanity
PermalinkThe default ajax event for submit button is 'mousedown'. This creates problem as keypress inside texfields won't submit the form.
Set the #ajax['event'] = "click" in the submit button, and you can submit the form by hitting enter in one of the textfields
Pressing the ENTER key within
PermalinkPressing the ENTER key within a textfield triggers the click event of the form's first submit button. Triggering Ajax in this situation leads to problems, like breaking autocomplete textfields, so we bind to mousedown instead of click.
See http://drupal.org/node/216059
Source: ajax_pre_render_element()
created element with ajax ,not act autocomplete
Permalinki have a select option value , in change create a text field with auto complete feature,
every thing is ok , but autocomplelete of this element not work!!!
part of my code
<?php
$form['azlocation']=array(
'#type' => 'select',
'#title' => 'location',
'#options' => array(1,2,3),
'#default_value' => 1,
'#description' => t('select your news location.'),
'#ajax' => array(
'event' => 'change',
'callback' => 'country_select_f',
//'path' =>'roadtonowhere',
'wrapper' => 'city-term',
'method' => 'replace',
'effect' => 'fade',
),
);
$form['field_terms_city']= array(
'#markup' => '<div id="city-term"></div>');
country_select_f(&$form, $form_state){function
$form['city_list_item2'] =array(
'#type' => 'textfield',
'#title' => t('select city (optional)'),
'#autocomplete_path' => 'mycustompath/autocomplete',
'#weight' => -1,
'#attributes' => array('id' =>'city-term-select'),
);
?>
where is the problem?
perhaps this is related to this
Permalinkhttp://api.drupal.org/comment/48143#comment-48143
Clicking an ajax link more than once
PermalinkI'm able to use the above to create ajax links, but they only work once. Any ideas on how to make the ajaxified links work again after they've been clicked?
Check your wrapper
PermalinkLook at the HTML that's returned -- if your wrapper ID isn't the same as what you're replacing, or if your replacement doesn't also include the ID, the second time will fail because the wrapper doesn't exist!
Simple directions: How to use AJAX
PermalinkThe description above is hard to understand. For the vast majority of cases, this is all you need to know when you wish to write AJAX:
Once you know that, it's quite easy to use AJAX. This is what you do:
<?phpif (! empty($form_state['values']['nameinput'])) {
// The user has typed in a name
$default_name = check_plain($form_state['values']['nameinput']);
$default_answer = t('Your name is ') . $default_name;
}
else {
// The user hasn't typed a name, yet.
$default_name = '';
$default_answer = t('I do not know your name yet.');
}
form['nameinput'] = array(
'#type' => 'textfield',
'#title' => 'Name',
'#default_value' => $default_name,
);
form['response'] = array(
'#type' => 'item',
'#markup' => $default_answer,
);
?>
<?phpform['response'] = array(
'#type' => 'item',
'#markup' => $default_answer,
'#prefix' => '<div id="replace_this">',
'#suffix' => '</div>',
);
?>
<?phpform['nameinput'] = array(
'#type' => 'textfield',
'#title' => 'Name',
'#default_value' => $default_name,
'#ajax' => array(
'wrapper' => 'replace_this',
'callback' => 'update_name_callback',
),
);
?>
<?phpfunction update_name_callback($form, &$form_state) {
return $form['response'];
}
?>
The function can generate the form element any way you like, but this is the easiest way to do it and is compatible if Javascript is turned off. If the function needs to know which form element triggered it, it can refer to $form_state['triggering_element']['#array_parents'].
That's it. Making a form work with AJAX isn't much more difficult than making it work without AJAX.
How to make an entire form submit via ajax
PermalinkWhat's the best way to make an entire form submit via ajax, running the _submit and _validate handlers as normal (so errors are displayed, form items are marked red, etc), then updating some arbitrary markup on the page once submission is successful? Creating an effect similar to how the old ajax module worked for D6.
I can't seem to find this use case anywhere in the documentation or examples module even though it seems very straight forward and typical.
Attaching #ajax to the submit button isn't enough, the form can only be submitted once and appears to ignore the typical _validate and _submit functions. At least, it doesn't color code anything or display messages.
I ended up doing something like this to get the form to submit and validate via ajax, but it doesn't feel correct. Specifying the form's DOM id as the wrapper to replace is an unstable solution, as that can change with multiple form instances. It also doesn't allow updating any other DOM elements on successful submission.
function productsearchbar_savesearch_form($form, &$form_state) {$form["wrapper"] = array("#markup" => "<div class='inline-messages'></div>");
$form["name"] = array(
"#type" => "textfield",
"#required" => true,
"#title" => "Name"
);
$form["submit"] = array(
"#type" => "submit",
"#value" => "Send",
"#ajax" => array(
"callback" => "productsearchbar_savesearch_form_callback",
"wrapper" => "productsearchbar-savesearch-form",
"effect" => "fade",
'keypress' => TRUE,
)
);
return $form;
}
function productsearchbar_savesearch_form_callback($form, &$form_state) {
$messages = theme('status_messages');
if($messages){
$form["wrapper"] = array("#markup" => "<div class='inline-messages'>$messages</div>");
}
return $form;
}
function productsearchbar_savesearch_form_validate($form, &$form_state) {
if(empty($form_state['values']['name'])){
form_set_error('', t('No terms provided'));
}
}
function productsearchbar_savesearch_form_submit($form, &$form_state) {
drupal_set_message(t('Your form has been saved.'));
}
How to programmatically bind events to forms inserted via ajax
PermalinkSo, I declared a form to use the #ajax properties and it works when printed directly in a page using print render(drupal_get_form("my_form")) and all that.
However, often times ajax forms will be brought into the page via ajax, like inserting a form into a modal window, or loading the DOM of the form somewhere into the page via $.ajax
I would expect that any ajax behaviors attached to a form injected via ajax would bind when Drupal.attachBehaviors(); is called, like every other part of Drupal, but this is not the case. Ajax enabled forms injected via ajax come through dead, and stay dead.
I have made sure that all required libraries are included, like drupal.ajax and jquery.form.
I did notice that ajax parameters for forms rendered traditionally were stored in Drupal.settings.ajax, and that this settings array was not generated via Drupal.attachBehaviors() for forms that were injected via ajax.
Does anyone have any ideas on this?
ajax events on ajax inserted elements
PermalinkThis issue is also holding up the solution here: http://stackoverflow.com/questions/11341399/drupal-7-how-to-change-multi...
I wonder (out loud ;-) ) how the Hierarchical Select module handles this.
Similar in D6
PermalinkHi,
is there similar solution in Drupal 6 ?
BR
Piotr
May be this is a simpler example for drupal ajax
Permalink<?phpfunction assignment_user_add_form($form,&$form_state)
{
Global $countries,$states;
$values =isset($form_state['values'])?($form_state['values']):array();
if(!empty($values['country']))
{
$states = db_query('SELECT id,state_name FROM {assignment_state} WHERE cid = :cid',array(':cid'=>$values['country']))->fetchAllKeyed(0,1);
}
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#default_value' => !empty($values['name']) ? $values['name'] : '',
'#description' => 'Please Enter a valid name',
'#required' => TRUE,
'#weight' => -5
);
$form['pic'] = array('#type' => 'managed_file',
'#title' => t('Profile Pic'),
'#default_value' =>!empty($values['pic']) ? $values['pic'] : '',
'#description' => 'Try to upload a thumbnail image',
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
),
'#upload_location' => 'private://',
'#required' => TRUE,
'#weight' => -4,
);
$form['region'] = array('#type' => 'fieldset',
'#title' => t('Region'),
'#weight' => -3,
'#collapsible' => TRUE,
);
$form['region']['country'] = array('#type' => 'select',
'#title' => t('Country'),
'#options' =>$countries,
'#default_value' =>!empty($values['country'])?$values['country'] : '',
'#ajax' => array(
'callback' => '_replace_state_callback',
'wrapper' => 'dependent-select-state',
'method' => 'replace',
),
'#required' => TRUE,
'#weight' =>-2,
);
$form['region']['state'] = array('#type' => 'select',
'#title' => t('State'),
'#options' =>$states,
'#default_value' =>!empty($values['state']) ? $values['state'] : '',
'#prefix' => '<div id="dependent-select-state" style="float:left;">',
'#suffix' => '</div>',
'#required' => TRUE,
'#weight' =>-1,
);
$form['save'] = array(
'#type' => 'submit',
'#title' => t('Save'),
'#value' => t('Save'),
'#weight' => 0,
);
return $form;
}
function _replace_state_callback($form,&$form_state)
{
return $form['region']['state'];
}
?>
can be chanage wrapper id dynamically
PermalinkI need to change wrapper id dynamically please suggest me that this is possible in drupal ,
custom Java script not working after validation
PermalinkI have created a custom form and addition java script on some field
This is working fine when page load but after submit display some require message it,s fine ,but my additional java script not working ,
this is my form code
function youtube_video_form_setp1($form,&$form_state) {
$form = array();
$form['youtube_form'] = array(
'#type' => 'fieldset',
'#title' => t('Share video with us.'),
'#weight' => 5,
'#prefix' => '',
'#suffix' => '',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['youtube_form']['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#size' => 60,
'#required' => TRUE,
);
$form['youtube_form']['desc'] = array(
'#title' => t('Description'),
'#type' => 'textarea',
'#description' => t ('Please Enter video Description'),
'#required' => TRUE,
);
$form['youtube_form']['category'] = array(
'#type' => 'select',
'#title' => t('Category'),
'#options' => youtube_video_import_get_taxonomy_value(12),//12 video category id
'#description' => t('Select video category.'),
'#required' => TRUE,
'#prefix' => '',
'#suffix' => '',
);
$form['youtube_form']['new-category'] = array(
'#type' => 'textfield',
'#title' => t('Category title'),
'#required' => TRUE,
'#default_value' =>0,
'#size' => 35,
'#prefix' => '',
'#suffix' => '',
);
$form['return_url'] = array (
'#type' => 'hidden',
'#value' =>'home',
);
$form['youtube_form']['submit'] = array(
'#type' => 'submit',
'#value' => t('Next>>'),
'#ajax' => array(
'callback' => 'youtube_video_form_setp1_process',
'wrapper' => 'youtube-render-second-form',
'method' => 'html',
'effect' => 'fade',
),
);
$form['#attached'] = array(
drupal_get_path('theme', 'danland') . '/scripts/jquery.cycle.all.js' => array(
'type' => 'file',
)
);
/*$form['#attached']['js'] = array(
drupal_get_path('module', 'ajax_example') . '/ajax_example.js' => array(
'type' => 'file',
),*/
return $form;
}
And this is my java script code ..
jQuery(document).ready(function($) {
$('.slideshow').cycle({
fx: 'fade' , timeout: 8000, delay: 2000});
alert('all');
/* js for youtube form*/
jQuery('span#pre-video-category select').change(function() {
cvalue = jQuery(this).val();
if(cvalue == 0 && cvalue!=''){
jQuery('span#new-video-category input[type="text"]').val('');
jQuery('span#new-video-category').show();
}else{
jQuery('span#new-video-category').hide();
jQuery('span#new-video-category input[type="text"]').val(0);
}
});
});
I want to track on span#pre-video-category select
please suggest me
thanks
Anil kumar ravat
Your JS file isn't written
PermalinkYour JS file isn't written the prescribed way. You have to wrap it in a specific structure:
(function($){
Drupal.behavior.yourCodeName = {
attached : function(settings, context) {
// Your initialisation code.
}
}
})(jQuery);
The outer closure means you can use $ inside the closure to mean jQuery. The attach function gets called when Drupal is ready to initialise it. The context specifies what part of the page is being re-initialised.
You should also use the .once() function to ensure you don't try to reinitialise part of the HTML that's already been processed.
Your code is only run once, when the page loads. With Ajax the code might have to run again on a piece of HTML that's just been loaded.
Check any third party module with a JS file to see how it's done.