Search code examples
javascriptdropdown

Limit dropdown string to just the first word in the string


I have a dropdown element with values like these:

<option value="Bulletins">Bulletins, bulletin_type, comments, engineering, keywords, language_type, model_name, offLine_type, option_code, product_code, product_type, security_group</option>

<option value="Communication">Communication, comments, communication_type, engineering, keywords, language_type, model_name, offLine_type, option_code, product_code, product_type, security_group</option>

I can't change the format but I can add javascript to the page. I want to be able to just display the string up to the first comma but have the rest of the string available for other things I need to do. Is this possible? Scott


Solution

  • You can move the text into a data attribute and set the text to the portion you want.

    document.querySelectorAll("#sel option").forEach((opt) => {
       opt.dataset.orgText = opt.textContent;
       opt.textContent = opt.textContent.split(",")[0];
    });
    
    document.querySelector("#sel").addEventListener("change", (evt) => {
      const selectedOption = evt.target.querySelector("option:checked");
      console.log({
        value: selectedOption.value,
        data: selectedOption.dataset.orgText,
        text: selectedOption.textContent,
      });
    });
    <select id="sel">
    <option></option>
    <option value="Bulletins">Bulletins, bulletin_type, comments, engineering, keywords, language_type, model_name, offLine_type, option_code, product_code, product_type, security_group</option>
    <option value="Communication">Communication, comments, communication_type, engineering, keywords, language_type, model_name, offLine_type, option_code, product_code, product_type, security_group</option>
    </select>