2

I would like to have a default text in an Exposed Views Search form that says something like 'type in a keyword to search' which will disappear if the user clicks on the text field and reappear if the user removes the cursor and didn't type anything. I would like the title of the field which is added through Views to become the text in the text field box. Should I use pure jQuery to add the text to the box? Or should I use hook_form_FORM_ID_alter() to add the jQuery and change the location of the title?

3 Answers 3

9

You can do this by implementing hook_form_alter() in a custom module.

function custom_form_alter(&$form, &$form_state, $form_id) {
    if ($form['#id'] == 'search-block-form') {  
        $search_text = 'Your search text here';
        $form['search_block_form']['#default_value'] = $search_text;
        $form['search_block_form']['#attributes'] = array(
        'onfocus' => "if (this.value == '$search_text') {this.value = '';}",
        'onblur' => "if (this.value == '') {this.value = '$search_text';}");
    }
}
1
  • Now it is searching for 'Your search text here' when landing on the search page. With Views Exposed filters setting the default value doesn't work.
    – Adam S
    Commented Sep 6, 2011 at 9:00
0

I think the best solution is the both, hook_form_alter() like this, you can add the placeholderattribute for fallback.

And after, for browsers that don't understand placeholder, you can use pure jQuery.

0

Unfortunately, because the way Views Exposed filters is structured setting the default attribute also sets the filter which is rendered later. Using the jQuery Input Example plugin I added some custom code to a helper module.

First, I need to add the jQuery to the page. Since I think I might use this in the admin theme also I didn't put it in a theme so it gets added to the overlay.

function helper_preprocess_page (&$vars) {
  // Let's add some js to page for the search box.
  $path = drupal_get_path('module', 'helper');
  drupal_add_js($path . '/js/jquery.example.min.js');
  drupal_add_js($path . '/js/helper.js');
}

In the helper.js file I added the code to execute the helper plugin.

(function ($) {
  Drupal.behaviors.helper =  {
    attach: function(context, settings) {
      $('input#edit-search-job-aggregation').example('Enter a location (optional)'); 
      $('input#edit-search-api-views-fulltext').example('Enter a keyword (optional)');   
    }
  };
})(jQuery);

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.