views:

173

answers:

4

Say I have this div:

<div id='myDiv'>
  <input type='text' id='foo' size='30' />
</div>

and i run this javascript code:

($("#foo").val('bar');

If I then do:

alert($("#myDiv").html());

or

alert(document.getElementById('myDiv').innerHTML);

I get only the original copy of the html where the value of foo textbox is still blank. I would like to get a current copy of the html with a value='bar' attribute added to foo's html code.

How can this be done?

+1  A: 

You really want to use the jquery().clone() function. This will let you clone the #mydiv and then insert your clone in the iBox.

var clone = $('#myDiv').clone();
$('#iBox').append(clone);
PetersenDidIt
Looking at iBox its very limited, no events on open or close. yes its light weight but it might be too light weight for what you are doing.
PetersenDidIt
I don't think having events would help with this, would they?
Click Upvote
You would be able to only have one #mydiv and pull it out of the iBox on close rather then it getting deleted from the dom.
PetersenDidIt
A: 

Why not just copy the input's value property to its attribute before generating the innerHTML? Note that this will change the effect of any Reset type button you may have.

Neil
A: 

Hi - as I understand it, you want to display "{text from within the div} = bar"? If this is the case, the code below works for me in both FF and IE:

<html>
<head>
 <title>Hello</title>
 <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
 <script type="text/javascript"> 
  $(document).ready(function()
  {
   $("#foo").val('bar');
   alert(($(".myDiv").text()) + ($("#foo").val()));
  });
 </script>
</head>
<body>
 <div class='myDiv'>
  Value = <input type='text' id='foo' size='30' />
 </div>
</body>
</html>
Brandi
+1  A: 

You could try setting the value param directly but I'm pretty sure that still won't affect the output of either .html() or .innerHTML:

$('#foo').attr('value', 'foo');

Instead, why not add it in yourself:

var html = $('#foo').html();
if (html.indexOf('value=') == -1)
    html.replace(/^<input/, '<input value="' + $('#foo').val() + '"');
Rob Van Dam