1

可能重复:
如何使用 JavaScript 验证表单?

我想使用 javascript 那就是我的表单不会在刷新时或通过空白字段向表中添加任何数据我的代码在这里

<form id="form1" name="form1" method="post" onsubmit="return validateForm()" action="">
    Name <input type="text" name="name" /> <br />
    Website <input type="text" name="website" /> <br />
    Description <input type="text" name="description" /> <br />
      <input type="submit" name="submit" value="Submit"/>
    </form>
    <?php
    global $wpdb;
    $wpdb->query("insert into ".PRO_TABLE_PREFIX."tutorial ( name, website, description )
    values('{$_POST['name']}','{$_POST['website']}','{$_POST['description']}')");

    ?>
4

1 回答 1

2

尝试:

演示

    <form id="form1" name="form1" method="post" onsubmit="return validateForm();" action="aaa">
        Name <input type="text" class="txt" name="name" /> <br />
        Website <input type="text" class="txt" name="website" /> <br />
        Description <input type="text" class="txt" name="description" /> <br />
        <input type="submit" id="submit" value="Submit"/>
    </form>

    <script type="text/javascript">
        function validateForm(){
            var arr = document.getElementsByClassName('txt');
            var errors = '';
            for(var i=0;i<arr.length;i++){
                if(!arr[i].value){
                    errors += arr[i].getAttribute('name') + ' cannot be blank\n';
                }
            }
            if(errors.length){
                alert(errors);
                return false;
            }
        }
    </script>
于 2012-12-07T10:53:46.800 回答