开发者

how to validate form array input field using javascript

i have input field i.e.

form name='myform' action='' method='post' onsubmit= return validate(this); /
input type='text' name='sort_order[]' id='sortorder' 

i want to use javascript on submit button to check all of the inputs have integer value.

{<javascript>}

 function validate(ob开发者_开发技巧j)
{
     if(obj.elements['sort_order[]'].length == 0)
    {
        alert(" Please Enter Value!");  
        return false;
    }   


}

Please help. thanks


Andrew's solution is pretty good, however I'd suggest using a regular expression rather than parseInt, e.g.

form.onsubmit = function() {
  var re = /^\d+$/;

  for(var i = 0; i < form.elements.length; i++) {

    if(form.elements[i].type == "text" && !re.test(form.elements[i].value)) {
      ...

Because:

var s = '08';
parseInt(s) == s // false;

also integers of the form 2e3 will return false for both parseInt and RegExp tests. It depends on how robust or general the function needs to be.


Ok, your description is a bit vague but here is one solution.

If your html looks like this

<!DOCTYPE html>
<html>
  <head>
    <title>Form</title>
  </head>
  <body>
    <form id = "important_form">
      <input type = "text" value = "0"/>
      <input type = "text" value = "0"/>
      <input type = "text" value = "0"/>
      <input type = "submit" value = "submit"/>
    </form>
    <script type = "text/javascript" src="validate.js"></script>
  </body>
</html>

Then you could use javascript similar to this

form = document.getElementByID("important_form");
//This will execute when the user presses the submit button.
form.onsubmit = function() {
  //Loop through all form elements.
  for(var i = 0; i < form.elements.length; i++) {
    //If the form element is a text input and the value is not an integer
    if(form.elements[i].type == "text" && 
       parseInt(form.elements[i].value) != form.elements[i].value) {
      alert("Please enter an integer value"); //Replace this with whatever you want
                                              //to do with invalid results
      return false; //Stops the submit from continuing.
    }
  }
  return true;
}


     var k1=document.getElementsByName("version[]");
     var y1=k1.length;
     console.log(y1);
      for(var x=0;x<y1;x++)
            {
         if(k1[x].value==null||k1[x].value=="")
                {
                alert("please fill version");
              return false;
       }
         }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜