Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically select an option inside a variable using jQuery

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.

like image 283
Fariz Luqman Avatar asked Dec 22 '16 02:12

Fariz Luqman


1 Answers

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>
like image 159
Mr. Polywhirl Avatar answered Oct 19 '22 15:10

Mr. Polywhirl