mcfred
mcfred

Reputation: 1391

How to set default value in a dropdown

I have the following code :

 render: function (data, type, product) {
                            var s = $('<select id="qty_dropdown" />');
                            for (i = 1; i <= data; i++) {
                                $('<option />', { value: i, text: i }).appendTo(s);
                            }
                            $('#qty_dropdown>option:eq('+data+')').prop('selected', true);
                            return s.prop("outerHTML");

                        }

I am simply trying to set the selected value = data. However, this displays the first option value instead of the last option value. So for example, if data == 10, then the dropdown displays 1 instead of 10. Any ideas?

Upvotes: 2

Views: 54

Answers (3)

gaetanoM
gaetanoM

Reputation: 42044

Because the dropdown is a newly created element and it is not part of the DOM you cannot use:

$('#qty_dropdown>option:eq('+data+')').prop('selected', true);

Instead, you can use the variable:

s.find('option:eq('+(data-1)+')').prop('selected', true);

You need to use data - 1 because the options in a dropdown go from 0 to n -1

In any case the simplest way to select an option in a dropdown is .val():

var data = 10;

var s = $('<select id="qty_dropdown" />');
for (i = 1; i <= data; i++) {
    $('<option />', { value: i, text: i }).appendTo(s);
}
s.val(data);
// just to see ...
s.appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Taplar
Taplar

Reputation: 24965

Since the element you are trying to select is the last one, you can just update it.

var data = 10;
var s = $('<select id="qty_dropdown" />');
for (i = 1; i <= data; i++) {
  $('<option />', {
    value: i,
    text: i
  }).appendTo(s);
}
//You need to perform the find on the `s` element, not on the page
s.find('option:last').attr('selected', true);
console.log(s.prop("outerHTML"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Manoj Mathew
Manoj Mathew

Reputation: 41

You can try this:

$('#qty_dropdown option[value="'+data+'"]').prop('selected', true)

Upvotes: 0

Related Questions