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 ?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

8 Comments

For more info on why to use this you can refer to this question
@George Thank you. Edited.
Excellent ! Thanks for the help, I am surprised this question was never asked before :)
@BiswasKhayargoli My pleasure, have a great day.
@Kinduser just a question! How to do the same thing if there was a textarea instead of input ?
|
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>

2 Comments

Thanks!!, but I will have to mark the above answer correct as he did it first :)
Not a problem at all :)))
0

try this

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.