Search code examples
javascriptjqueryjquery-selectbox

Jquery select option default option text


I'm trying to populate several select boxes having the same class using jQuery. This is my code

populateFieldMapping: function (data,obj) {
        jQuery('.field-mapping select').each(function()
        {
            var option = '<option value="" data-custom-id="_select_">' + "please select a field" + '</option>';
            jQuery.each(data, function (i, res) {
                option += '<option value="' + res.id + '" data-custom-id="' + dataID + '"  data-custom-name="' + res.name + '">' + res.name + '</option>'
            });
            $(this).html(option);
            obj.select2();
        });
    },

My HTML

<div class="field-mapping">
     <select id="podio-fields-mapping" class="form-control" tabindex="-1">
     </select>
     <select id="podio-fields-mapping" class="form-control" tabindex="-1">
     </select></div>

Everything is working fine except I am only getting the "Please select a field" default option for only the first select box. What could be wrong? I am getting all values in every select box.

obj = $('.form-control');

Solution

  • Your code has some typos, I'm afraid:

    jQuery('.field-mapping select').each(function()
    {
        var option = '<option value="" data-custom-id="_select_">' + "please select a field" + '</option>', // <- here you have a ',' instead of ';'
        jQuery.each(data, function (i, res) {
                option += '<option value="' + res.id + '" data-custom-id="' + dataID + '"  data-custom-name="' + res.name + '">' + res.name + '</option>'
        }}); // <- here you have an aditional '}'
        $(this).html(option);
     });
    

    Please check you console for errors.

    You also can't have two elements with the same id="podio-fields-mapping" in your markup.

    Working fiddle.