1

While using Simple Hierarchical Select Module, I have 2 levels of Hierarchy for my Phone. enter image description here

However I want to add the label for Child list like:

enter image description here

Is this possible? then how?

1

You Can do with custom jquary with set Intervel function.

Eg: i have attached screenshot at bottom

//Add label to state //on change first level(here country)

$('select.shs-select-level-1').change(function(){

    var $aSelected = $('.shs-wrapper-processed').find('label'); 

    if( $aSelected.hasClass('Extra-Label1') ){
        $('.Extra-Label1').text("State");
    }
    else{
        $('select.shs-select-level-2').before('<label class="Extra-Label1">State</label>');
    }

});

//Add label to city

$('select.shs-select-level-2').change(function(){

    var $aSelected = $('.shs-wrapper-processed').find('label'); 

    if( $aSelected.hasClass('Extra-Label2') ){
        $('.Extra-Label2').text("City");
    }

    else{           
        $('select.shs-select-level-3').before('<label class="Extra-Label2">City</label>');
    }
});

//The above code is ok, but last label will loss after change any select levels so needs add in set intervel function

setInterval(function(){
    var $aSelected = $('.shs-wrapper-processed').find('label'); 
    var $bSelected = $('.shs-wrapper-processed').find('select');
    if( $aSelected.hasClass('Extra-Label2')&& $bSelected.hasClass('shs-select-level-3') ){
        $('.Extra-Label2').text("City");
    }
    else{
        $('select.shs-select-level-3').before('<label class="Extra-Label2">City</label>');
    }

},1000);

enter image description here

|improve this answer|||||
  • I which file we can write this script ? – Devidas Kadam Jul 1 '16 at 5:53
  • Devidas, you can write the above script in theme custom js file – Soliyappan Oct 21 '16 at 9:49
2

I know I'm late, because this answer has been answered long time ago, but I don't think this is the right way to do it, especially with the java script interval function – it might work but in many cases may cause a problem.

For those who need the same result I suggest to use this java script code which is based on action when the ajaxStop event is triggered.

First you nedd to create a java script file in your module directory, for exapmle: YOUR_MODULE_NAME/js/custom_shs_behaviors.js with the following code:

/**
 * @file
 * Custom behaviors for Simple hierarchical select:
 *   Change the first option text from "- None -" to whatever you want (default: "- Any -").
 *   Create labels for each level.
 */
 (function($) {
  Drupal.behaviors.customShsBehaviors = {
    attach: function (context, settings) {

      // Helper function for an option text replacement.
      // use: optionObj.replaceOptionText(); for default replacement from '- None -' to '- Any -'.
      // or optionObj.replaceOptionText('Foo'); to replace the '- None -' with 'Foo'.
      $.fn.replaceOptionText = function(replacement) {
        var replacement = replacement ? replacement : '- Any -';
        if ($(this).text() == Drupal.t('- None -')) {
          $(this).text(Drupal.t(replacement));
        }
      };

      // Function that helps to get the select element width including its padding and margin.
      $.fn.getSelectWidth = function() {
        var width = Math.round($(this).wrap('<span></span>').outerWidth(true));
        $(this).unwrap();
        return width;
      }

      // Define labels.
      var labels = ['Label-1', 'Label-2', 'Label-3'];

      // act when the ajaxStop event is triggered (there are no more Ajax requests being processed.)
      // see: @link http://api.jquery.com/Ajax_Events/ @endlink
      $('.shs-wrapper-processed').ajaxStop(function(event, xhr, settings) {

        $("select.shs-select").each(function(level) {

          // fix the SHS bug - new level that is being created has the same ID as the previous one.
          // make sure that each select has an ID and the class corresponding to the level.
          // YOU CAN USE THESE TWO LINES ONLY IF YOU ARE USING SHS WITH THE ABILITY TO ADD NEW LEVELS.
          $(this).attr('id', $(this).attr('id').replace(/(.*)select-(\d+)/, "$1select-" + (level+1)));
          $(this).attr('class', $(this).attr('class').replace(/(.*)level-(\d+)/, "$1level-" + (level+1)));

          // Replace the first option text using the helper function for an option text replacement.
          $("option", this).first().replaceOptionText();

          // Get label width.
          var labelWidth = $(this).getSelectWidth();

          // Create label.
          if ($("label[for='" + $(this).attr('id') + "']").length == 0) {
            $(this).parent().before(
              "<label for='" + $(this).attr('id') + "' style='display: inline-block; width: " + labelWidth + "px'>" + labels[level] + "</label>"
            );
          }

          // Remove the label if the select element has just been removed by clicking any option on lower level.
          // There might be several Ajax requests bound with this action,
          // so we have to make sure that our "removing process" will be executed at most once.
          // See: @link http://api.jquery.com/one/ @endlink
          $("option:not(:selected)", this).one("click", function() {
            $(".shs-wrapper-processed").parent().find("label").each(function() {
              if ($(this).attr('for').slice(-1) > level+1) {
                $(this).remove();
              }
            });
          });
        });
      });
    }
  };
})(jQuery);

And attach the java script file to your form. You can do it by using the hook_form_alter() in your theme or module file:

/**
 * Implements hook_form_alter.
 */
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {

  switch($form['#id']) {
    case 'YOUR-FORM-ID' :
      $form['#attached']['js'][] = drupal_get_path('module', 'YOUR_MODULE_NAME') . '/js/custom_shs_behaviors.js';
    break;
  }
}

You're done! With this code you can set the label for each level of your shs and even change the default option text, for example: from - none - to - any -.

|improve this answer|||||
  • Hi,I have a problem with using this function: $("#edit-field-country-region-tid-select-1 option[value='0']").replaceOptionText('-Select region-'); How can I make use of this? I tried many options, and I have no idea how to apply this function to specific option. – rukya Aug 17 '16 at 9:19
  • Working fine ,but label not remove . – Pankaj Yogi Jun 10 '17 at 12:06
0

Some developers may wish to use the pre-existing label over the top category to represent a title for the hierarchial select (rather than a header for the top category).

Here's another (jQuery) way you could achieve a similar effect, using a locational hierarchy for the demo:

In your custom js you can add a top level label when the document is "ready" - custom way or the preferred Drupal.behaviors way (neither demonstrated).

$('select.shs-select-level-1').before('<label class="shs-label">' + Drupal.t('Region') + '</label>');

Then monitor for any changes to the entire container. If one is detected, you can clear all the labels of a custom class and then re-attach all the classes where jQuery can ignore exceptions

$('#field-select-a-city-add-more-wrapper').change(function () {
    $('#field-select-a-city-add-more-wrapper').find('label.shs-label').remove();
    $('select.shs-select-level-1').before('<label class="shs-label">' + Drupal.t('Region') + '</label>');
    $('select.shs-select-level-2').before('<label class="shs-label">' + Drupal.t('Country') + '</label>');
    $('select.shs-select-level-3').before('<label class="shs-label">' + Drupal.t('State') + '</label>');
    $('select.shs-select-level-4').before('<label class="shs-label">' + Drupal.t('City') + '</label>');
});
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy