【问题标题】:jQuery function that check empty input tags in PHP, AJAX Form在 PHP、AJAX 表单中检查空输入标签的 jQuery 函数
【发布时间】:2018-01-31 04:01:47
【问题描述】:

我进行了研究,但最终还是坚持使用我的 PHP AJAX 表单。我的表单已经可以使用,但我想添加一些用户体验,例如当 HTML 输入标记为空或条件不匹配时将边框更改为红色。

这是我的 PHP,AJAX 表单的作品。我通过 PHP 验证了用户在服务器端的输入,而不是客户端,然后将 JSON 格式的错误返回给我的 jQuery/Javascript 代码。我想知道哪些 HTML 输入标签为空或失败,以便添加这些输入标签的类。

这是我从 PHP 返回的 JSON,我转换为 JSON.parse n jQuery/Javascript 代码。

{
    "errors": [{
        "firstname": "Missing First name"
    }, {
        "lastname": "Missing Last name"
    }]
}

如果我的 JS 代码有错误,我检查了响应

var json = JSON.parse(response);
if (json.hasOwnProperty('errors') && json.errors.length > 0) {
     // I want to call a function here that detect which input tags are empty then add a class.                
   }else {
       //execute other function
  }  

PHP 代码

<?php

$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : null;
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : null;

$errors = []; //array for errors
$noError = "No error found";
if(empty($_POST['firstname'])){
    $errors[]['firstname'] = 'Missing First name';
}else{
    $firstname = sanitizedData($_POST['firstname']);
}
if (empty($_POST['lastname'])) {
    $errors[]['lastname'] = 'Missing Last name';
}else{
    $lastname = sanitizedData($_POST['lastname']);
}


if(!empty($errors)){
    $result_array = array('errors' => $errors);
    echo json_encode($result_array);
    exit();
}else{
    echo json_encode($noError);   
}

//sanitized data from user inputs
function sanitizedData($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

?>

【问题讨论】:

  • 代码有什么问题?
  • 嗨@Eddie,我的代码没有问题,相反我需要一些帮助来检测输入标签是否为空或验证失败。

标签: javascript php jquery ajax


【解决方案1】:

我想在这里调用一个函数来检测哪些输入标签是空的 然后添加一个类。

为所有需要验证的输入添加一个公共类。在if 语句中调用function

使用 document.querySelectorAll 获取所有需要验证的输入元素。使用forEach 迭代并检查是否为空。然后使用classList.add在里面添加一个错误类

function checkInput() {
  var getAllInput = document.querySelectorAll('.ipClass');
  getAllInput.forEach(function(item) {
    if (item.value === '') {
      item.classList.add('error')
    }
  })
}
.error {
  border: 1px solid red;
}
<input type="text" class="ipClass">
<input type="text" class="ipClass">
<input type="text" class="ipClass">
<input type="text" class="ipClass">
<button onclick="checkInput()">Check</button>

【讨论】:

  • 嗨@brk,你能解释一下为什么你使用forEach而不是for循环吗?
  • @darkRabbit forEach 是一种内置数组方法,& 对我来说它比 for 循环更简洁明了,如果你愿意也可以使用 for 循环
  • 我明白了,在问这里之前我有这个代码 for(i=0; i = 0) { input.classList.add('error'); } } 但什么也没发生
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 2016-12-21
  • 2013-10-29
  • 2012-05-18
相关资源
最近更新 更多