Jquery — how can i change ` element with jQuery's `.val()` method doesn't work, while settings the value of an `` will work: – yunzen Jan 28 '19 at 14:43

4 Answers4

2
var $html = $('<div><select class="target"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select></div>');
$html.find('.target').val('2');
$('body').html($html);

I think this code should produce the correct output, the output that you are looking for. Rather than adding raw html, I appended an actual jQuery variable in your dom.

Also there was a typo for class name, it should be class="target"

Here is the working fiddle link

kyle
  • 691
  • 1
  • 7
  • 17
chiragchavda.ks
  • 532
  • 7
  • 25
1

I can not understand what's meant by your code html($html.prop('outerHTML'))

If you want let $html into document you can create a div

$html.appendTo('div');
treyBake
  • 6,440
  • 6
  • 26
  • 57
0

In case of a select HTMLElement, the selection is maintained internally in the selectedIndex attribute of the element object. Using $.val() on a select also maintains this correctly, but when $.prop('outerHTML') is used it's lost. When you append elements to the DOM, it's preserved:

var $html = $('<div><select class="target"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select></div>');
$html.find('.target').val('2');
$('body').html('').append($html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>

<div class="target"></div>
marekful
  • 14,986
  • 6
  • 37
  • 59
0

var $html = $('<div><select class="target"><option value="1">1</option><option value="2">2!</option><option value="3">3</option></select></div>');
$html.find('.target').val(2);
$('body').append($html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
yunzen
  • 32,854
  • 11
  • 73
  • 106