Languages
[Edit]
EN

JavaScript - how to access input element?

11 points
Created by:
AnnLen
9210

In JavaScript it is possible to acces input element in following way.

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>
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join