EN
JavaScript - access input element
11
points
In this article, we would like to show you how to access input element using JavaScript.
Short solution
var input = document.getElementById('my-input');
input.value = 'This text has been set from javascript code...';
var input = document.forms['my-form']['my-input'];
input.value = 'This text has been set from javascript code...';
var forms = document.forms['my-form'];
var input = form.elements['my-input']; // form.elements.namedItem('my-input');
input.value = 'This text has been set from javascript code...';
var form = document.getElementById('my-form');
form['my-input'].value = 'This text has been set from javascript code...';
1. Input id
attribute example
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
input {
padding: 10px;
width: 300px;
}
</style>
</head>
<body>
<input id="my-input" type="text" value="" />
<script>
var input = document.getElementById('my-input');
input.value = 'This text has been set from javascript code...';
</script>
</body>
</html>
2. document.forms
property example
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
input {
padding: 10px;
width: 300px;
}
</style>
</head>
<body>
<form name="my-form">
<input id="my-input" type="text" value="" />
</form>
<script>
var forms = document.forms;
var form = forms['my-form'];
var input = form['my-input'];
input.value = 'This text has been set from javascript code...';
</script>
</body>
</html>
3. Form elements
property example
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
input {
padding: 10px;
width: 300px;
}
</style>
</head>
<body>
<form name="my-form">
<input id="my-input" type="text" value="" />
</form>
<script>
var form = document.forms['my-form'];
var input = form.elements['my-input']; // form.elements.namedItem('my-input');
input.value = 'This text has been set from javascript code...';
</script>
</body>
</html>
Note: with this approach we can access easly input elements when name conflict occured.
4. Form id
attribute example
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
input {
padding: 10px;
width: 300px;
}
</style>
</head>
<body>
<form id="my-form">
<input id="my-input" type="text" value="" />
</form>
<script>
var form = document.getElementById('my-form');
var input = form['my-input'];
input.value = 'This text has been set from javascript code...';
</script>
</body>
</html>