i have a form which user enters some data, could be checkboxes, radio buttons, textfields, etc
when user click submit button, i want to refresh the page with whatever data that was entered
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
</head>
<body id="ref">
<form>
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
</form>
<input type="button" onclick="c()" value="submit">
<script type="text/javascript">
function c()
{
var o = document.getElementById('ref');
o.innerHTML = '';
var n = document.createElement('p');
var nam = document.getElementById('name');
n.innerHTML = "Your name is: " + nam;
o.appendChild(n);
var a = document.createElement('p');
var ag = document.getElementById('age');
a.innerHTML = "Your age is: " + ag;
o.appendChild(a);
//how do i get the info from the form? because both nam and ag are coming up null
}
</script>
</body>
</html>
my guess this is not working is because the page refreshes then tries to fetch the element by id which is not there anymore.. whats the correct way of doing this??
You’re confusing objects with their properties. Here, you’re getting the
HTMLInputElementinstance for the “age” field:But here you’re using that object as though it were a simple value:
The
HTMLInputElementobject has avaluefield you can use for that:Separately, you’re completely destroying the page by doing this:
…because you’ve given the
bodyelement the ID “ref”. Completely replacing thebodyelement completely replaces thebodyelement, so you can’t rely on objects that only exist as subordinates of that element.The usual thing is to have an element to fill in, and (optionally) to remove the elements you no longer need. For instance (live copy):
HTML:
(Note I moved the button into the form for convenience.)
JavaScript:
There, when the button is pressed, I remove the form and fill in the “result” div.
You could add the “result” div dynamically if you wanted (live copy):
HTML:
JavaScript:
You can access the fields using a briefer and somewhat more natural syntax if you change your
idvalues tonamevalues instead (live copy):HTML:
JavaScript:
Further reading: