I add js file with drupal_add_js in hook_form_alter, it is ok and I see it in list of js loaded in page, but when I submit form and form not validate and return to that form (after validation failed) I don't see js files that added to form, why this happened? and how can add my js file in that form after validation failed ?

some part of my code

function mymodle_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'news_node_form') {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodulejsfile.js'); //, array('scope' => 'footer','weight' => 10));

code work correctly in add and edit form, but when form submit and validation failed it show validation error but my js file not loaded in page (I checked html source and check firebug script files), but there is not my js file,

  • This question appears to be off-topic because it is about code you wrote, for which you want to write better code, or you want to understand why it doesn't work, but you didn't show the code you are using, or the part of the code that is relevant for the question. See Help Center.
    – Mołot
    Commented Jun 8, 2014 at 13:32
  • @Mołot come on man , it is clear , dont need code, I add some js in hook_form_alter but when validation failed that js files not loaded in browser, it means that only in first load of page drupal_add_js taked effect I update question with more descrption.
    – Yuseferi
    Commented Jun 8, 2014 at 13:38
  • If JS is included and there is no error neither in it nor in the way you are adding it, then it works - it has to, and your question is about nothing.
    – Mołot
    Commented Jun 8, 2014 at 13:42
  • 2
    You need to use #attached. drupal.stackexchange.com/questions/70015/…
    – mikeytown2
    Commented Jun 8, 2014 at 13:50
  • @Mołot code work when first time form load (in add or edit) but when form submit and not passed validation true (there is some requirement in form data entry ,...) it return to the form, but there is no js file after from not validated :(
    – Yuseferi
    Commented Jun 8, 2014 at 14:14

1 Answer 1


Javascripts are lost when the form is rebuilt when using drupal_add_js(). Use $form['#attached'] instead. Also, it's better to use hook_form_FORM_ID_alter() instead of a general hook_form_alter(). hook_form_alter() will run for every form on the page. Try using the below:

function mymodule_form_news_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'mymodule') . '/js/mymodulejsfile.js',

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.