EN
JavaScript - access input element
11 points
In this article, we would like to show you how to access input element using JavaScript.
xxxxxxxxxx
1
var input = document.getElementById('my-input');
2
input.value = 'This text has been set from javascript code...';
3
4
var input = document.forms['my-form']['my-input'];
5
input.value = 'This text has been set from javascript code...';
6
7
var forms = document.forms['my-form'];
8
var input = form.elements['my-input']; // form.elements.namedItem('my-input');
9
input.value = 'This text has been set from javascript code...';
10
11
var form = document.getElementById('my-form');
12
form['my-input'].value = 'This text has been set from javascript code...';
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
input {
7
padding: 10px;
8
width: 300px;
9
}
10
11
</style>
12
</head>
13
<body>
14
<input id="my-input" type="text" value="" />
15
<script>
16
17
var input = document.getElementById('my-input');
18
19
input.value = 'This text has been set from javascript code...';
20
21
</script>
22
</body>
23
</html>
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
input {
7
padding: 10px;
8
width: 300px;
9
}
10
11
</style>
12
</head>
13
<body>
14
<form name="my-form">
15
<input id="my-input" type="text" value="" />
16
</form>
17
<script>
18
19
var forms = document.forms;
20
21
var form = forms['my-form'];
22
var input = form['my-input'];
23
24
input.value = 'This text has been set from javascript code...';
25
26
</script>
27
</body>
28
</html>
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
input {
7
padding: 10px;
8
width: 300px;
9
}
10
11
</style>
12
</head>
13
<body>
14
<form name="my-form">
15
<input id="my-input" type="text" value="" />
16
</form>
17
<script>
18
19
var form = document.forms['my-form'];
20
var input = form.elements['my-input']; // form.elements.namedItem('my-input');
21
22
input.value = 'This text has been set from javascript code...';
23
24
</script>
25
</body>
26
</html>
Note: with this approach we can access easly input elements when name conflict occured.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
input {
7
padding: 10px;
8
width: 300px;
9
}
10
11
</style>
12
</head>
13
<body>
14
<form id="my-form">
15
<input id="my-input" type="text" value="" />
16
</form>
17
<script>
18
19
var form = document.getElementById('my-form');
20
var input = form['my-input'];
21
22
input.value = 'This text has been set from javascript code...';
23
24
</script>
25
</body>
26
</html>