jqueryformsjquery-chosen

How to populate text inputs with data values from Chosen multiselect?


I'm using Chosen jQuery multiselect-plugin to create selects from database. My table looks like this:

|   id   |   text1   |   text2    |
-----------------------------------
|   rs1  |  rs1text  |  rs1text2  |
|   rs2  |  rs2text  |  rs2text2  |
|   rs3  |  rs3text  |  rs3text2  |

How to populate text input fields #textinput1 and #textinput2 with data-values from text1 and text2? All i'm able to get to inputs are values of id. When I select 2 options (rs1 and rs3), this is what I get in console:

[rs1: {…}, rs3: {…}]
rs1: {text2: 'rs1text2', text1: 'rs1text ', id: 'rs1'}
rs3: {text2: 'rs3text2', text1: 'rs3text ', id: 'rs3'}

Nothing comes to inputs #textinput1 and #textinput2. I expect the inputs to get data values as texts like this: #textinput1 - rs1text, rs3text or rs1text (line break) rs3text.

This is my code so far:

jQuery(".chosen").chosen({ 
        placeholder_text : "Select", 
        search_contains: true,
    });

jQuery(function() {
    jQuery("#chosen_select").on('change', function() {
        var selected=[];
        jQuery("#chosen_select :selected").each(function() {
            selected[jQuery(this).val()]=jQuery(this).data();
            });
        jQuery("#textinput1").val(selected["text1"]).prop('readonly', true);
        jQuery("#textinput2").val(selected["text2"]).prop('readonly', true);
        console.log(selected);
    })
})

Solution

  • Here's a possible solution.

    There are 2 noteworthy modifications here (compared with your code).

    1. selected is initialized as an object ({}) not an array.
    2. when pulling the text1 and text2 values, we dig down into the selected object using the key that was selected.
      jQuery("#chosen_select").on("change", function () {
        var selected = {};
        jQuery("#chosen_select :selected").each(function () {
          selected[jQuery(this).val()] = jQuery(this).data();
        });
        const selectedText1Values = [];
        const selectedText2Values = [];
        for (key in selected) {
          const data = selected[key];
          selectedText1Values.push(data.text1);
          selectedText2Values.push(data.text2);
        }
        
        jQuery("#textinput1").val(selectedText1Values.join(", ")).prop("readonly", true);
        jQuery("#textinput2").val(selectedText2Values.join(", ")).prop("readonly", true);
        console.log(selected);
      });
    

    I don't know exactly what your HTML looks like but I made a guess and put this into play in this codepen. https://codepen.io/bunnymatic/pen/bGLjoBw

    Hopefully this helps out.