【问题标题】:form validation using javascript in codeigniter在 codeigniter 中使用 javascript 进行表单验证
【发布时间】:2011-05-26 05:13:39
【问题描述】:

嗨,我有一个从数据库填充的 jquery 表:

<?php 
$attributes = array('name' => 'users');

echo form_open('users/action',$attributes);?>
<table class="data display datatable" id="example">
    <thead>
        <tr>
          <th>Username</th>
          <th>Name</th>
          <th>Nickname</th>
          <th>Birthday</th>
          <th>Sex</th>
          <th>Address</th>
          <th><input type="checkbox" id="select all"></th>
        </tr>
    </thead>
    <tbody> 
<?php foreach($query->result_array() as $row): ?>
        <tr class="even gradeC">
            <td><?php echo anchor('users/details/'.$row['usrID'],$row['usrName']);?></td>
            <td><?php echo $row['usrpFirstName'].' '.$row['usrpLastName'];?></td>
            <td><?php echo $row['usrpNick'];?></td>
            <td><?php echo $row['usrpBday'];?></td>
            <td><?php echo $row['usrpSex'];?></td>
            <td><?php echo $row['usrpAddress'];?></td>
            <td><input type="checkbox" name="checkID[]" id="checkID" value="<?php echo $row['usrID'];?>" />

              <label for="checkID"></label></td>
        </tr>
<? endforeach; ?>
    </tbody>
</table>
  <input type="submit" name="Delete" id="Delete" value="Delete" class="btn btn-orange" />
  <input type="submit" name="Edit" id="Edit" value="Edit" class="btn btn-orange" onclick="return validateForm()" />
  <input type="submit" name="AddUser" id="Add User" value="Add User" class="btn btn-orange" />
 </form>

正如您在下面看到的,我使用checkID[] 以便我可以获取每个用户的每个 id。 我确实在编辑按钮上创建了一个onlick,以便它检查 id 是否为空。这是我的js函数

<head>
<script type="text/javascript">
function validateForm()
{
var x=document.forms["users"]["checkID[]"].value
if (x==null || x=="")
  {
  alert("Please select user to edit.");
  return false;
  }
}
</script>
</head>

现在的问题是,即使我检查表中的一个用户,它仍然会发出警报..

即使我用这个:

<?php 
$attributes = array('name' => 'users' , 'onsubmit' =>"return validateForm()");

echo form_open('users/action',$attributes);?>

【问题讨论】:

    标签: php javascript codeigniter validation


    【解决方案1】:

    document.forms["users"]["checkID[]"] 将为您提供一个由 all 具有该名称的复选框组成的数组。您要求数组的 value 没有意义。您需要遍历它们以找出是否有类似这样的检查:

    function validateForm() {
       var checkboxes = document.forms["users"]["checkID[]"];
       for (var i = 0; i < checkboxes.length; i++) {
          if (checkboxes[i].checked) {
             return true;
          }
       }
    
       alert("Please select a user to edit.");
       return false;
    }
    

    我尚未对其进行测试,但该代码应该可以为您提供大致的思路。

    【讨论】:

    • 如果我在一个表中有两个用户,它可以工作,但如果表只有一个用户,它仍然会提醒我没有选中任何复选框,,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多