Get selected value from SHS via Javascript

Created on 23 March 2023, over 1 year ago
Updated 12 May 2023, over 1 year ago

Via Javascript, is it possible to get the value or text of the selected option within a SHS enabled field? I have tried a number of variations using Drupal.behaviors but can't seem to get it to work properly or consistently.

This code fires just once and only for the first select within my SHS enabled term reference field. My goal is to get the text of the final selected option and insert it into the title field.

(function ($, window, Drupal) {

  Drupal.behaviors.bpl_config = {
    attach: function (context, settings) {

      $(context).find('.shs-field-container select').addClass('tom-test').each(function () {

        $(this).on("change", function () {
          sval = $("option:selected", this).text();
          console.log('got val= ' + sval);
          $("#edit-title-0-value").val(sval);
        });

      });

    }

  };

})(jQuery, window, Drupal);

For reference, this simpler code snippet did the job for me on Drupal 7 using the Hierarchical Select module:

$("select[id^='my-field-und-hierarchical-select-selects-0']").on( "change", function() {
    sval = $("option:selected", this).text();
    if ( $(this).val() != "none") {
            $("#edit-title").val(sval);
    }
});
πŸ’¬ Support request
Status

Active

Version

2.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States todea

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @todea
  • The following code works for me to show a term of the third dropdown. (See dropdown.png.)
    $('#edit-field-assignedto-taxonomy').change(function() {
    $val = $('#edit-field-assignedto-taxonomy-shs-0-2').children('option:selected').text();
    console.log('got val= ' + $val);
    });

    Use Inspector tab of Web Developer Tools of browser (e.g Firefox) to find two id names above. (See developertools.png.)

Production build 0.71.5 2024