Mattew Trincanati
Mattew Trincanati

Reputation: 191

Issue not having a selected default option while populating select with ajax

I'm having a problem not being able to have a default selected option when i fill the select box with ajax call, i have the value, but not a default one, I want that the default one will be the first value i get from the call;

my HTML is (we will work on select2):

<div class="containerdiv">
    <select class="select1" name="dettaglio1">
    </select> <select class="select2" name="dettaglio2">
    </select> <select class="select3" name="dettaglio3">
    </select>
</div>

while the ajax call is that (Comments are for you):

loadEvento : function() {

            $select2 = $('.select2');
            luoghi.saveLuogo();  //dont care about
            $
                    .ajax({
                        url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
                        dataType : 'json',
//                        data: JSON.stringify(opzioniSelezionate.luogo),
                        success : function(data) {
                            console.log(data);
                            $select2.html('');
//                          SETTING 1st value as selected
                            var first_iteration = true;
                            $.each(data, function(key, val) {
                                var o = new Option(val,key);
                                  if (first_iteration) {
                      o.selected = true; // ALSO TRYED $select2.html(o);
                                      first_iteration = false;
                                  }
                                   $select2.append(o);
                            })
                        },
                        error : function(err) {
                            $select2.html('<option id="0">nessun dato disponibile</option>');
                            console.log(err);

                        }
                    });

        }

and my html after the call is(F12) :

<div id="select-4-button" class="ui-btn ui-icon-carat-d ui-btn-icon-right ui-corner-all ui-shadow">
  <span class="select2">&nbsp;</span>
  <select class="select2" name="dettaglio2">
  <option value="0">option1</option>
  <option value="1">option2</option>
  <option value="2">option3</option>
  <option value="3">option4</option
  ><option value="4">option5</option>
  </select></div>

Is the problem on span element? and why it's blank ?

Upvotes: 2

Views: 886

Answers (4)

Butani Vijay
Butani Vijay

Reputation: 4239

Use following once your options loaded :

$('.select2 option:eq(1)').prop('selected', true)

Here 1 is index.you can set default value by index easily. Change your success part to below code:

                 success : function(data) {
                            console.log(data);
                            $select2.html('');
//                          SETTING 1st value as selected
                            var first_iteration = true;
                            $.each(data, function(key, val) {
                                var o = new Option(val,key);
                                  if (first_iteration) {
                                      o.selected = true; // ALSO TRYED $select2.html(o);
                                      first_iteration = false;
                                  }
                                   $select2.append(o);
                            })
                         // Select the default value once all the options are loaded
                         $('.select2 option:eq(1)').prop('selected', true)
                      },

If there is 2 .select2 class then use index for .select2 ( Check This Link for same)

Upvotes: 1

Mattew Trincanati
Mattew Trincanati

Reputation: 191

Thank to Pugazh I modified his answer and came to this working solution:

 $("#select-4-button").children("span").html($('select[name=dettaglio2] option:first').text());

the full code:

loadEvento : function() {

            $select2 = $('.select2');
            luoghi.saveLuogo();  //dont care about
            $
                    .ajax({
                        url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
                        dataType : 'json',
//                        data: JSON.stringify(opzioniSelezionate.luogo),
                        success : function(data) {
                            console.log(data);
                            $select2.html('');
//                          SETTING 1st value as selected
                            var first_iteration = true;
                            $.each(data, function(key, val) {
                                var o = new Option(val,key);
                                  if (first_iteration) {
                      o.selected = true; // ALSO TRYED $select2.html(o);
                                      first_iteration = false;
                                  }
                                   $select2.append(o);
                            })
                         // Select the default value once all the options are loaded
                              $("#select-4-button").children("span").html($('select[name=dettaglio2] option:first').text());
                        },
                        error : function(err) {
                            $select2.html('<option id="0">nessun dato disponibile</option>');
                            console.log(err);

                        }
                    });

        }

I answered because is more clear the solution, but thumbs up his answer and comments that helped me.

(I've thumbed up everyone that helped, thanks a lot) ;)

Upvotes: 1

Pugazh
Pugazh

Reputation: 9561

Select the default value once all the options are loaded. Check below

loadEvento : function() {

            $select2 = $('.select2');
            luoghi.saveLuogo();  //dont care about
            $
                    .ajax({
                        url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
                        dataType : 'json',
//                        data: JSON.stringify(opzioniSelezionate.luogo),
                        success : function(data) {
                            console.log(data);
                            $select2.html('');
//                          SETTING 1st value as selected
                            var first_iteration = true;
                            $.each(data, function(key, val) {
                                var o = new Option(val,key);
                                  if (first_iteration) {
                      o.selected = true; // ALSO TRYED $select2.html(o);
                                      first_iteration = false;
                                  }
                                   $select2.append(o);
                            })
                         // Select the default value once all the options are loaded
                         $('select[name=dettaglio2]').val($('select[name=dettaglio2] option:first').val());
                        },
                        error : function(err) {
                            $select2.html('<option id="0">nessun dato disponibile</option>');
                            console.log(err);

                        }
                    });

        }

Upvotes: 2

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

$(".select2")[0].selectedIndex = 0;

You should try this when your select tag is already populated/.

Upvotes: 1

Related Questions