Ahamed Zulfan
Ahamed Zulfan

Reputation: 135

Multiple Forms with common JS validation

I'm a newbie to Javascript and jQuery. All I got was this JS function to validate my form. I've got some common fields in both the forms. Instead of calling to different function to validate to different form I want a single JS function to validate all the common fields in both the forms. FYI Both the forms are in different Pages.

JS

function check1(){
    var x = document.forms["form1"]["type"].value;
    if (x == null || x == "") {
        alert("Please Enter Type");
        return false;
    }

function check2(){
    var x = document.forms["form2"]["type"].value;
    if (x == null || x == "") {
        alert("Please Enter Type");
        return false;
    }

HTML

form1

<form name="form1" method="post" action="#" onsubmit="return check1()">
<input type="text" name="type" id="type">
</form>

form2

<form name="form2" method="post" action="#" onsubmit="return check2()">
<inout type="text" name="type" id="type">
</form>

Thanks in Advance. Please bear me I'm a newbie.

Upvotes: 0

Views: 181

Answers (1)

Don
Don

Reputation: 6852

Here's a common function for both forms: (i.e. instead of check1 and check2, use check).

function check(){
    var frm = document.forms["form1"] || document.forms["form2"];
    var x = frm["type"].value;
    if (x == null || x == "") {
        alert("Please Enter Type");
        return false;
    }
    return false;
}

Upvotes: 1

Related Questions