Jump to content

[SOLVED] JS validation


hassank1

Recommended Posts

I've many select boxes and textfields in my form

so I want to loop all selectbox and if they contain the value " ---select---" I want to show an alert (please fill all the fields)

 

and I want to loop all textfields and if one of them is empty I want to show an alert (please fill all the fields)

 

thanks..

Link to comment
Share on other sites

To make things easy set the valueof select options with the text "---select---" to an empty value.

 

<html>
<head>
<script type="text/javascript">

var requiredFields = ['select1', 'select2', 'input1', 'input2'];

function validate_form(formObj)
{
    for (var i=0; i<requiredFields.length; i++)
    {
        if (!formObj[requiredFields[i]].value)
        {
            alert('Please fill all the fields.');
            return false;
        }
    }
    return true;
}


</script>
</head>

<body>

<form name="test" onsubmit="return validate_form(this)">
Select 1:
<select name="select1">
<option value="">---Select---</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select><br>

Select 2:
<select name="select2">
<option value="">---Select---</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select><br>

Input 1:
<input type="text" name="input1"><br>

Input 2:
<input type="text" name="input2"><br>

<br>
<button type="submit">Submit</button>
</body>
</html>

Link to comment
Share on other sites

in the requiredFields I put all the elements names in my form right?

 

Yes, some people would probably build the script to just programatically go through every field in the form, but that can create a problem when you decide to have a field that is not required.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.