Saranga
Saranga

Reputation: 520

How to add both value and id to html drop down option tag dynamically

I'm trying to add options in to the select box dynamically. This is my HTML

<select id="RightPriceMulRetail" class="form-control"></select>

And this is my JavaScript code

$("#RightPriceMulRetail").get(0).options.length = 0;
$.each(data, function (index, item) {
 $("#RightPriceMulRetail").get(0).options[$("#RightPriceMulRetail").get(0).options.length] = new Option(item.sellPrice, item.qty);
});

This is working fine and result like this

<option value="qty">sell Price</option>

Now my question is i need to add ID attribute to option like bellow using my JavaScript

<option value="qty" id="someValue">sell Price</option>

Can any one help me with this.

Upvotes: 0

Views: 3619

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388436

You can create an element using jQuery syntax easily, then use .appendTo() to add that to the select

var $select = $("#RightPriceMulRetail").empty();
$.each(data, function (index, item) {
    $('<option />', {
        value: item.qty,
        text: item.sellPrice,
        id: 'someid'
    }).appendTo($select)
});

Demo: Fiddle

Upvotes: 2

Related Questions