11

Let say I have this variable html which contain these select options:

var html = '<select>'+
             '<option value="10">10</option>'+
             '<option value="20">20</option>'+
            '</select>';

How can I programmatically select an option which is inside the html variable so when I append them to somewhere, for example

$(this).children('div').append(html);

it will become like this:

<div> <!-- children div of the current scope -->
  <select>
    <option value="10" selected>10</option>
    <option value="20">20</option>
  </select>
</div>

How is it possible?


edit: the variable contents is generated from remote locations, and I must change the value locally before it is being appended into a div. Hence, the question.

edit 2: sorry for the confusion, question has been updated with my real situation.

6
  • You can append them and then update the selected property thereafter.
    – Terry
    Dec 22, 2016 at 2:04
  • @Terry that's the part I'm stuck until now. mind to share some answer? (please) wink-wink Dec 22, 2016 at 2:06
  • didnt this work ? var html = '<select><option value="10" selected>10</option><option value="20">20</option></select>'
    – Deep
    Dec 22, 2016 at 2:06
  • This can help you: stackoverflow.com/questions/314636/…
    – Arnaldo
    Dec 22, 2016 at 2:07
  • @Terry the variable html is generated and I have no control over them Dec 22, 2016 at 2:07

6 Answers 6

7

You can cast the HTML into a jQuery element and select the value at index 0. Then you can add it to the DOM.

Here is a simple jQuery plugin to select an option by index.

(function($) {
  $.fn.selectOptionByIndex = function(index) {
    this.find('option:eq(' + index  + ')').prop('selected', true);
    return this;
  };
  $.fn.selectOptionByValue = function(value) {
    return this.val(value);
  };
  $.fn.selectOptionByText = function(text) {
    this.find('option').each(function() {
      $(this).attr('selected', $(this).text() == text);                                 
    });
    return this;
  };
})(jQuery);

var $html = $([
  '<select>',
    '<option value="10">10</option>',
    '<option value="20">20</option>',
  '</select>'
].join(''));

$('#select-handle').append($html.selectOptionByIndex(0));
// or
$html.selectOptionByValue(10);
// or
$html.selectOptionByText('10');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select-handle"></div>

4
  • 2
    splendid. no any other words to say. $('#select-handle').append($html.selectOptionByIndex(0)); <<<< this is what I'm looking for. thank you Dec 22, 2016 at 2:21
  • @Mr.Polywhirl cool solution... that's why I like SO so much - always gives you something to learn :)
    – kukkuz
    Dec 22, 2016 at 2:26
  • just out of curiousity, would this statement this.find('option:eq(' + index + ')').prop('selected', true); end up making multiple selected option?
    – Jeffrey04
    Dec 22, 2016 at 6:16
  • @Jeffrey04 the :eq() part makes it select just the given index. If you set another one to selected, it will deselect the previous option, unless the <select> tag has the multiple property (which it doesn't in this case).
    – Schism
    Dec 22, 2016 at 8:36
5

You could try simply setting the value of the drop-down to the one you wish to 'select' - like $("#select_handle select").val( a_value );

For example, if a_value is 30 it will add the needed HTML to the DOM node. This would be my take:

$(function() {
  var html = '<select>' +
      '<option value="10">10</option>' +
      '<option value="20">20</option>' +
      '<option value="30">30</option>' +
      '<option value="40">40</option>' +
      '<option value="50">50</option>' +
    '</select>';

  // set a value; must match a 'value' from the select or it will be ignored
  var a_value = 30; 

  // append select HTML
  $('#select_handle').append(html);

  // set a value; must match a 'value' from the select or it will be ignored
  $("#select_handle select").val(a_value);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2>select added below</h2>
<div id="select_handle">
</div>

4

By default, the first option will be selected - if you want to do on any other set it so using the index as soon as the select is appended:

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

(this selects the second option)

See demo below:

var html = '<select>'+
             '<option value="10">10</option>'+
             '<option value="20">20</option>'+
            '</select>';
$('#select_handle').append(html);
$('#select_handle option:eq(1)').prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select_handle"></div>

3
  • can I select the option before the selectbox is being appended into #select_handle? thanks Dec 22, 2016 at 2:15
  • 1
    @FarizLuqman normally I wait for the DOM to update and use something like ng-init (because I use angular) but Mr. Polywhirl's answer is a new thing for me... :)
    – kukkuz
    Dec 22, 2016 at 2:35
  • 1
    on normal times, I will also do that by using solutions my fellow friends provided before him (again sorry for not clearing the question) but to update the element before the DOM is updated, that may take some advanced level of understanding, and hence, a new lesson to be learned by all :) Dec 22, 2016 at 2:39
3

selected="selected" will work

var html = '<select>'+
             '<option value="10">10</option>'+
             '<option value="20" selected="selected">20</option>'+
            '</select>';

            $('#select_handle').append(html);
2
  • The variable html is completely generated by remote location, and the only choice I have is to modify the content of the variable. Dec 22, 2016 at 2:10
  • $("#select_handle option[value=10]").attr('selected','selected'); will help
    – Payal2299
    Dec 22, 2016 at 2:17
3

You can do this in jQuery using the .attr() function and nth pseudo-selector.

Like so:

$("option:nth-child(1)").attr("selected", "");

Hope it helps! :-)

2

after the append, try $('#select_handle select').val("10"); or 20 or whatever value you want to select

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.