2

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');
});

1 Answer 1

5

.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);
Sign up to request clarification or add additional context in comments.

2 Comments

Close... but not quite. I tried both and got Uncaught TypeError: undefined is not a function. I think I may have to add the attributes via jquery after appending them to the element.
At what line you got the error , undefined is not a function usually because you are attempting call jquery function that does't allow because the option already wrap as DOM. What about you change to option.setAttribute("data-owner_id", item.owner_id)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.