4

$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').val('hi');
  console.log(parent.prop('outerHTML'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <input type='text' id="bar" value="" />
</div>

I have a container div with child input element, the initial value is empty, after that I change it's value using jQuery and try to get the changed html string using .prop('outerHTML'). However it returns:

<div id="foo"><input type="text" id="bar" value=""></div>

I need to return it as:

<div id="foo"><input type="text" id="bar" value="hi"></div>

Is this possible ?

George
  • 6,630
  • 2
  • 29
  • 36
Biswas Khayargoli
  • 976
  • 1
  • 11
  • 29

3 Answers3

4

You can use .attr() instead.

$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').attr('value', 'hi');
  console.log(parent.prop('outerHTML'));

  $('#txt').text('hello');
  console.log($('#par').find('#txt').prop('outerHTML'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <input type='text' id="bar" value="" />
</div>

<div id="par">
  <textarea id='txt'></textarea>
</div>

For more details - visit following link.

Community
  • 1
  • 1
kind user
  • 40,029
  • 7
  • 67
  • 77
1

Sure, use direct attrbite change, not element value.

$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').attr('value', 'hi');
  console.log(parent.prop('outerHTML'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <input type='text' id="bar" value="" />
</div>
VadimB
  • 5,533
  • 2
  • 34
  • 48
0

try this

$(document).ready(function() {
  var parent = $('#foo');
  parent.find('#bar').attr('value','hi');
  console.log(parent.prop('outerHTML'));
});
Vitaliy Ryaboy
  • 471
  • 2
  • 10