Search code examples
javascripthtmljquerycustom-data-attribute

Using jQuery to set HTML data attributes on a select option


How can I add HTML data attributes to a jQuery generated <select> <option>. I have the following code which programmatically sets the <options> of a select from the results of an Ajax query.

$request.then(function (data) {
    var p_id = $("[name='property_id']").val() || -1;
    for (var d = 0, l = data.length; d < l; d++) {
       var item = data[d];
       var option = new Option(item.text, item.id, false, (item.id === p_id ? true : false));
       // this doesnt work
       option.data('data-owner_id') = item.owner_id;
       option.data('data-property_id') = item.property_id;
       $element.append(option);
    }
    $element.trigger('change');
});

Solution

  • .data() method takes the key and value paired. Try this:

       option.data('owner_id', item.owner_id);
       option.data('property_id', item.property_id);
    

    Other than that, you can use .attr() method to add the attribute into your option. I will just give an example for you.

      option.attr('data-owner_id', item.owner_id);
      option.attr('data-property_id', item.property_id);
    

    As the option variable is not a jQuery object, then you can't call the jQuery method like above function. The another option is using native JavaScript .setAttribute().

    option.setAttribute('data-owner_id', item.owner_id);
    option.setAttribute('data-property_id', item.property_id);