How to get Value of Input Type Field from a Form in Javascript

Posted on

This is another article which is related with Javascript. The article itself still has a connection with another article titled ‘How to get Value of Input Type Field from a Form in Javascript’ which is available in this link. The difference on this article with the previously mentioned one is the existance of a form. There is one form which is defined in the example of snippet code attached in this article where the form itself will be used for the container of input type text HTML element and from the input type text HTML element itself, the value inserted will be extracted.

Below is the snippet code which is used to define a form :

<head>
<title>
Check Submit Form
</title>
</head>
<body>
<form id="user_form" onsubmit="return ValidationEvent()">
<input type="text" id="username"></input>
<input type="submit" id="submit_button"></input>
</form>
</body>
</html>

The most important thing is the form definition. An attribute which can be used to extract the value from the input type text HTML element available inside is the ‘onsubmit’ attribute. Fill the value of the attribute with the function which is defined in Javascript to do the process further. In the context of this article, the name of the function is ‘ValidationEvent’. The script which is used to define the function based on Javascript is shown below :

<script type="text/javascript"> 
function ValidationEvent(){ 
var username = document.getElementById("username").value; alert(username); 
} 
</script>

To be able to extract the value of a certain HTML element, for an example an input type text, the id of the input type text must be well-known for the value inserted can be extracted as shown in the snippet code above :

document.getElementById("username").value;

The id is ‘username’ which is defined in the HTML web page file as shown below :

<input type="text" id="username"></input>

To prove that the value which is inserted through the input type text HTML element, store it to a variable where in the Javascript snippet code above it is represented by a variable named ‘username’ as shown in the above and it is re-written below :

var username = document.getElementById("username").value;

And then alert the variable to display it in a pop-up window where the content of the variable will be printed on it.

One thought on “How to get Value of Input Type Field from a Form in Javascript

Leave a Reply