javascript问题

时间:2010-05-02 07:04:20

标签: javascript

我创建了一个动态表,通过单击“添加”按钮来追加行,我希望如果没有在表的所有行中输入值,用户就无法提交页面。 我该如何实现这一目标 代码是

<html>
<head>
 <script type="text/javascript">
 function addRowToTable()
 {
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  var iteration = lastRow+1;
  var row = tbl.insertRow(lastRow);
  var cellLeft = row.insertCell(0);
  var textNode = document.createTextNode(iteration);
  cellLeft.appendChild(textNode);
  var cellRight = row.insertCell(1);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'txtRow' + iteration;
  el.id = 'txtRow' + iteration;
  el.size = 40;
  cellRight.appendChild(el);  
 }
 function validation()
 {
                var a=document.getElementById('tblSample').rows.length;
                for(i=0;i<a;i++)
                {
   alert(document.getElementById('tblSample').txtRow[i].value);//this doesnt work
                }
  return true;
 }
 </script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <form  name ='qqq' action="sample.html">
  <p>
   <input type="button" value="Add" onclick="addRowToTable();" />
   <input type="button" value="Submit" onclick="return validation();" />
  </p>
  <p>
   <table border="1" id="tblSample">
    <tr>
     <td>1</td>
     <td>The 1st row</td>
    </tr>
   </table>
  </p>
 </form>
</body>
</html> 

请建议

1 个答案:

答案 0 :(得分:0)

  1. 将验证添加到表单的onsubmit:
  2. ..表格onsubmit =“return validate(this)”

    1. 循环表单内容(假设您正确添加了输入)
    2.   function validate(theForm) {
            var found = false;
            for(var i=0, n=theForm.elements.length; i < n;i++) {
            if (theForm.elements[i].name.indexOf('txtRow')==0 && theForm.elements[i].value!="") {
              found=true;
              break; // no need to hang around longer
            }
          }
          return found;
        }