Append select box options dynamically with attributes

Viewed 10410

I need to append extra data to my select box options. here is my code.

Html:

<select id="questionNumber" class="form-control">
   <option>Select Number</option>
</select>

JQuery:

$.each(result.data, function (key, value) {
    $("#questionNumber").append($('<option>', {
        value: value.id,
        text: value.number
    }));
});

So i can add value and text but i want to append attributes also to this appended option like

data-marks = value.mark

So my expected result would be like

<select id="questionNumber" class="form-control">
   <option>Select Number</option>
   <option value="170" data-mark="2">1</option>
   <option value="171" data-mark="3">2</option>
</select>

What should i do for this? Thanks.

4 Answers

This is a similar example and more complete:

var cadena_user_pais = ($(this).attr('id')).split("_");
var id_user_pais = cadena_user_pais[2];
var request = 'view_tipoNIF';
//tipo de NIF
        $.ajax({
            url: "fetch_single_users.php",
            method: "POST",
            data:{id_user_pais:id_user_pais,request:request},
            dataType: "json",
            success:function(data)
            {
                //alert('hola');
                var html='';
                $.each(data, function (key, value) {
                    html +='<option value="' + value.id + '">' + value.NIF + '</option>';
                });             
                $("#select_user_tipoNIF").append(html);
            }   //success
        });
Related