JavaScript: How to get value from nested form in iframe?
Aug 12, 2004 • Javascript • HTMLWhen dealing with nested forms within an iframe, retrieving form values can be challenging. Here’s an updated guide to simplify the process.
Main Page (PageOne.html
)
<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
<script>
function getFormValue() {
const iframe = document.querySelector('iframe[name="PageTwo"]');
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
const formValue = iframeDoc.querySelector('form[name="Members"] input[name="Search"]').value;
alert(formValue);
}
</script>
</head>
<body>
<button onclick="getFormValue()">Get Value</button>
<iframe name="PageTwo" src="PageTwo.html" width="100%" height="100"></iframe>
</body>
</html>
Nested Page (PageTwo.html
)
<html>
<body>
<form name='Members'>
<input type='text' name='Search' value='Chris'>
</form>
</body>
</html>
Explanation
- HTML Structure: The main page contains a button and an iframe. The nested page includes a form with an input field.
- JavaScript Function: getFormValue accesses the iframe, retrieves the nested document, and extracts the value from the form input field.
- Compatibility: This approach works across modern browsers.
Conclusion
By utilizing modern JavaScript methods, you can easily access nested form values within iframes, enhancing the interactivity of your web applications.