Retrieving value of a dynamically created input field

Hello,

I’ve dynamically created a new field by using appendTo.

i.e.

$("<input type='text' id='field' value='1'>").appendTo("body");

If I try to access the value of this dynamically generated field (i.e. $(“#field”).val()), I don’t have any value returned. I understand this may be because jquery doesn’t detect it as being a part of the DOM or something along those lines.

Any ideas what I’ll need to do in order to get a value successfully returned?

Thanks.

Here is another way of doing it where you build the input element from scratch. At the end of the build process the new element value is displayed as an alert().

[HIGHLIGHT=“”]
<!doctype HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>

<html>

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=windows-1252”>
<title>Value of Append Field</title>
<script type=“text/javascript”>
<!–
function addInput()
{ var elem=document.createElement(“input”);
elem.setAttribute(“type”,“text”);
elem.setAttribute(“id”,“field”);
elem.setAttribute(“value”,“1”);
//
document.body.appendChild(elem);
alert("Field value= "+document.getElementById(“field”).value)
}
window.onload=addInput;
//–>
</script>
</head>

<body>

</body>

</html>

Your example seems to work on a test page that I quickly put together.

You may need to provide a test page of your own, so that we can diagnose the problem that you’re facing.

My simple test page:


<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
</body>
</html>

script.js


$(function () {
    $('<input type="text" id="field" value="test value">').appendTo('body'); 
    alert($('#field').val());
});