Use the same JavaScript function for different HTML forms

Posted by Shek on August 11, 2011 under HTML, JavaScript | Be the First to Comment | Total View: 6,155 views

In this post, I am going to show how to use the same JavaScript function for different HTML forms, this could help in situations when multiple forms need to preform the same operation but with different inputs.

The aim of this exercise is to use one single JavaScript function to alert out the value of 2 different textfields (one at a time) from 2 HTML form by clicking the corresponding button.

Firstly, we create 2 different HTML forms with different values in textfields within the “body” section:

1
2
3
4
5
6
7
8
9
10
11
<body>
<form id="form1">
    <input type="text" id="textfield1" value="This is from textfield 1">
    <input type="button" value="Display Textfield 1 message">
</form>
 
<form id="form2">
    <input type="text" id="textfield2" value="This is from textfield 2">
    <input type="button" value="Display Textfield 2 message">
</form>
</body>

Then we create a JavaScript function in the “head” section for alerting out a message, the key element of this is to have one input parameter for the function.

1
2
3
4
5
6
7
8
<head>
<script type="text/javascript">
function showtextfieldmsg(text)
{
    alert(text);
}
</script>
</head>

Back to the 2 forms, we now add onclick() action to the 2 buttons to trigger the javascript function when the button is clicked, and in order to distinct which textfield’s message is going to display, we go add the ID.value of the textfield as the function parameter in order for the function to know which textfield is. Notice that “.value” after the ID means to get the value of that element with the ID:

1
2
3
4
5
6
7
8
9
<form id="form1">
    <input type="text" id="textfield1" value="This is from textfield 1">
    <input type="button" onclick="showtextfieldmsg(textfield1.value);" value="Display Textfield 1 message">
</form>
 
<form id="form2">
    <input type="text" id="textfield2" value="This is from textfield 2">
    <input type="button" onclick="showtextfieldmsg(textfield2.value);" value="Display Textfield 2 message">
</form>

All together we have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<html>
<head>
 
<script type="text/javascript">
function showtextfieldmsg(text)
{
    alert(text);
}
</script>
 
</head>
<body>
 
<form id="form1">
    <input type="text" id="textfield1" value="This is from textfield 1">
    <input type="button" onclick="showtextfieldmsg(textfield1.value);" value="Display Textfield 1 message">
</form>
 
<form id="form2">
    <input type="text" id="textfield2" value="This is from textfield 2">
    <input type="button" onclick="showtextfieldmsg(textfield2.value);" value="Display Textfield 2 message">
</form>
 
</body>
</html>

This is just a simple example to show how to achieve the goal, it could help to develop into some more complex operations.

Not what you want? Try a Search

Add A Comment

*