javascript - Validate HTML form fields if it is specified with required attribute - Stack Overflow

I created a JSP page and I have many forms each in different tabs. So I have added a single submit butt

I created a JSP page and I have many forms each in different tabs. So I have added a single submit button mon to all forms(So the button is outside of the <form> tag). On each tab, when the submit is clicked, the appropriate forms are being submitted using JQuery. In all forms some form fields are required. And I have specified those fields with the required attribute like the following

<div class="control-group">
        <label class="control-label input-label" for="hostname">Host :
                    <span class="requiredField"> * </span>
            </label>
        <div class="controls">
            <input type="text" class="inputstyle" name="hostname" placeholder="host" required="required" />
</div>

The problem is when I click on submit button, it does not validate fields which are required. If the submit button is inside the form, it's working. But I need mon submit button. How to solve this?

I am just thinking in JQuery I am submitting form with form action value. So before submitting is it possible to call function to validate form by passing form ID and evaluate the required fields? If so, please help me to code.

Thanks

UPDATE 1

<button type="submit" id="submitbtn" class="btn btn-primary inputstyle" onclick="submitForm();">SUBMIT</button>

JQuery for this

function submitForm() {
            var $submitform=$('#formId').val();

            //validateForm($submitform); // I have not created this function.
            $('#'+$submitform).submit();
    }

I created a JSP page and I have many forms each in different tabs. So I have added a single submit button mon to all forms(So the button is outside of the <form> tag). On each tab, when the submit is clicked, the appropriate forms are being submitted using JQuery. In all forms some form fields are required. And I have specified those fields with the required attribute like the following

<div class="control-group">
        <label class="control-label input-label" for="hostname">Host :
                    <span class="requiredField"> * </span>
            </label>
        <div class="controls">
            <input type="text" class="inputstyle" name="hostname" placeholder="host" required="required" />
</div>

The problem is when I click on submit button, it does not validate fields which are required. If the submit button is inside the form, it's working. But I need mon submit button. How to solve this?

I am just thinking in JQuery I am submitting form with form action value. So before submitting is it possible to call function to validate form by passing form ID and evaluate the required fields? If so, please help me to code.

Thanks

UPDATE 1

<button type="submit" id="submitbtn" class="btn btn-primary inputstyle" onclick="submitForm();">SUBMIT</button>

JQuery for this

function submitForm() {
            var $submitform=$('#formId').val();

            //validateForm($submitform); // I have not created this function.
            $('#'+$submitform).submit();
    }
Share Improve this question edited May 27, 2013 at 11:01 Coder asked May 27, 2013 at 10:40 CoderCoder 7,07613 gold badges58 silver badges87 bronze badges 3
  • which javascript? I havn't tried any form validation till yet. Now if I do not give input also, the form is submitting – Coder Commented May 27, 2013 at 10:47
  • I just created a function like that and passing the form id. But after that I don't know how to code to find the required fields. – Coder Commented May 27, 2013 at 10:55
  • I am using JSP. When the form is submitted, it calls the Struts action – Coder Commented May 27, 2013 at 10:56
Add a ment  | 

4 Answers 4

Reset to default 1

Assume you have 2 forms (form1 and form 2) to submit on button click... you can call the following function on button click event.

function SubmitAllForms()
{
    document.forms.form1.submit();
    document.forms.form2.submit();
}

I think that below code will help you to solve your issue

HTML

   <form action="insertserverdata.php" id="myForm">
        <input type="text" name="userName">
         <input type="text" name="userPass">
        <input type="submit">
      </form>

JS

 var formRules={userName:{required:true},userPass:{required:true}};

 $("#myForm").validate({rules:formRules});

 $("#myForm").submit(function(event){

 if(! $("#myForm").valid()){

   return;

 }

 });


//Also you can get your form fields by using below code

  var values = {};
  $.each($('#myForm').serializeArray(), function(i, field) {
     values[field.name] = field.value;
  });          

ASSUMPTION: you click on tab, okay thats great you could create a hidden input and change it's value based on the tab you pressed lets illustrate more: you have form1,form2 and form3 on three tabs to toggle between so when you click on specific tab lets say tab1 which leads to form1 onclick you need to call method setVariable "which I made up" this method sets the value of your hidden input to let's say 1, example:

<div id="tab1" onclick="setVariable(1)">

now in you js you have this method:

function setVariable (value){
    document.getElementById('our hiddin input id').value= value;
}

now what? okay now it's time to validate onclick of your submit button you should call the method validateMyForm but which form?? well the form that have the same number as your hidden field watch that:

<input type="submit" onclick="validateMyForm(document.getElementById('hidden input').value)"/>

then in your js:

function validateMyForm(val){
    //use a switch or if-else to know which form you're validating and also which action should be submitted
}

that's pretty much the Idea goodluck

You can validate your data using client or server side scripts. You have asked for a javascript solution here, which is valid. As the javascript will prevent anything from being submitted unless the data is valid.

You need a switch or if statement to choose which form to submit. You'll need to have an identifier and this is algorithm:

AS you are using a form ID You only have to validate a form if you require certain fields pleted. getElementByID for the form id is perfect, use the if or switch to choose which form is to be validated and then submitted

eg if id 'lname1' (for form1) is not nothing then and use the javascript function validate() to check all fields of THAT form are filled. You will then have to have error checks, if more than one form has been filled, of once one field in a form has input, the other forms are disabled.

You could also run the if statement- on whether or not the form has been disabled.

To tell you the truth, it would probably be easier and chance for less errors to have a submit button for each for,.

example names:

function Validate()
        {


        // create array containing textbox elements
        var inputs = [document.getElementById('fname'), document.getElementById('lname'), document.getElementById('email'), document.getElementById('messagetxt')];

        var error;

        for(var i = 0; i<inputs.length; i++)
        // loop through each element to see if value is empty
        {
            if(inputs[i].value == '')
            {
                error = 'Please plete all fields.';
                alert(error);
                return false;
                }
        }
     }


     <form onsubmit="return Validate();"  action="contact.php" method="post" name="contact1" id="contact1"  >


        <input class="input" type="text" placeholder="First Name" name="fname" id="fname" />


        <input class="input" type="text" placeholder="Last Name" name="lname" id="lname"/>

        <input class="input" type="email" placeholder="Email Address" name="email"  id="email"/>

      <textarea placeholder="Message" name="messagetxt" id="messagetxt"></textarea>

    </form>  

     <form onsubmit="return Validate();"  action="contact.php" method="post" name="contact2" id="contact2" >
 //insert form details

    </form>  

        <input type="submit" value="submit" name="submit"  />

See this fiddle:

http://jsfiddle/yvytty/b3qdN/

If you need more feedback or clarity pls ask.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745047356a4608180.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信