1

I am populating a select element dynamically through an ajax call that returns a JSON object with several attributes like so:

$.ajax({
        type: "GET",
        url: "get_data.php",
        data: {value:someValue},
        dataType: "json", 
        cache: false,
        success: function(dataSet){
            $("#mySelect").empty().append('<option value="">default option</option>');
            if (!$.isEmptyObject(dataSet)){
                $.each(dataSet, function(i, data){
                    var option = $("<option>");
                    option.val(data.id);
                    option.text(data.description);
                    option.data("test", 1);
                    $("#mySelect").append(option);
                });
            }

            $("#mySelect").removeAttr("disabled");
        },
        error: function(data){
            alert("Populate mySelect Error: " + data.error);
        }
    });

The bit about option.data("test", 1) was me playing around with the idea of adding additionally returned attributes to my dynamically created option elements. This doesn't seem to be working. Any insight on how I can get my additional data attached to my option elements? I'm pretty new to jQuery and client side scripting, so any help is greatly appreciated!

5
  • 2
    What you have should work. Note though, that adding data in jQuery will not be visible in the HTML source, only by accessing the object through jQuery itself. Commented Apr 28, 2014 at 13:18
  • What you mean by not working? Commented Apr 28, 2014 at 13:19
  • it should work.. how are you saying it is not working Commented Apr 28, 2014 at 13:19
  • That was my problem Rory. I was checking the HTML source. Thanks! Commented Apr 28, 2014 at 13:32
  • possible duplicate of How can I add a jQuery .data() attribute to a dropdownlist option element - don't think it's possible with data but using rohan's answer below it works Commented Apr 28, 2014 at 13:37

1 Answer 1

0

Try to use attr() like,

option.attr("data-test", 1);
Sign up to request clarification or add additional context in comments.

1 Comment

I dont see any problem in option.data("test", 1)

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.