【问题标题】:How do I get the input validation to see if user input already exists in the table?如何获取输入验证以查看表中是否已存在用户输入?
【发布时间】:2018-01-08 07:17:41
【问题描述】:

感谢您查看此问题。我试图通过在表中找到输入值时不允许它存储来验证输入值。我正在努力找到它存储的变量,以便我可以将其放入验证中。

这是我的代码:

    var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u00D7");
  span.className = "close";
  span.appendChild(txt);
  myNodelist[i].appendChild(span);
}

// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
  close[i].onclick = function() {
    var div = this.parentElement;
    div.style.display = "none";
  }
}

// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
  if (ev.target.tagName === 'LI') {
    ev.target.classList.toggle('checked');
  }
}, false);

// Create a new list item when clicking on the "Add" button
function newElement() {
  var li = document.createElement("li");
  var inputValue = document.getElementById("myInput").value;
  var t = document.createTextNode(inputValue);
  li.appendChild(t);
  if (inputValue === '' || inputValue === ) {
    alert("You must write something!");
  } else {
    document.getElementById("myUL").appendChild(li);
  }
  document.getElementById("myInput").value = "";

  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u00D7");
  span.className = "close";
  span.appendChild(txt);
  li.appendChild(span);

  for (i = 0; i < close.length; i++) {
    close[i].onclick = function() {
      var div = this.parentElement;
      div.style.display = "none";
    }
  }
}

我正在尝试将我的验证放在 IF 语句中。

【问题讨论】:

  • 使用 ajax 调用将每个 keyup 函数的输入值与数据库进行比较。在输入字段下方或旁边添加错误范围并相应显示。
  • 这里有语法错误:if (inputValue === ''|| inputValue === ) {
  • 我把第二个位留空,因为我不知道该放什么值

标签: javascript jquery html css validation


【解决方案1】:

Ypu 需要在 newElement 之前添加另一个方法,如下所示。

var eleExist = function(eleValue){
  var lis = document.getElementById("myUL").getElementsByTagName("li");
  return lis.find(x => x.value.toLowerCase() === eleValue.toLowerCase());
}

然后

function newElement() { 
  ....
  ....
     var inputValue = document.getElementById("myInput").value;
      if (inputValue === '' || eleExist(inputValue) ) {
        alert("You must write something!");
      }
}

上面的东西应该可以工作。请注意,我没有尝试,因此您可能需要进行一些测试。

【讨论】:

    【解决方案2】:

    为了节省内存但不节省时间的方式,您可以添加一个函数来验证并在 if 语句中调用它:

    function newElement() {
      var li = document.createElement("li");
      var inputValue = document.getElementById("myInput").value;
      var t = document.createTextNode(inputValue);
      li.appendChild(t);
      if (inputValue === ''|| notDuplicated(inputValue) ) {
        alert("You must write something and you cannot add the same place 
      twice!");
      } else {
        document.getElementById("myUL").appendChild(li);
      }
      // etc...
    }
    //add this 
    function notDuplicated (text) {
      //list of all previously entered values
      var list = document.getElementById("myUL").getElementsByTagName("li");;
      for (var item of list) {
        if (item.value === text) {
        //text value already inserted before
        return true;
        }
      }
      //this means the value was not entered before
      return false
    }
    

    或者我喜欢的方式 为了节省时间而不是节省内存的方式,您可以轻松地将值存储在对象中 - 更多地使用内存,但您可以跳过添加用于验证的新功能-:

    //make sure this one is global not inside the function
    window.insertedTexts = {};
    function newElement() {
      var li = document.createElement("li");
      var inputValue = document.getElementById("myInput").value;
      var t = document.createTextNode(inputValue);
      li.appendChild(t);
      //check if we have it in our new object
      if (inputValue === ''|| window.insertedTexts[inputValue] ) {
        alert("You must write something and you cannot add the same place 
      twice!");
      } else {
        //and add each new value to the object you created
        window.insertedTexts[inputValue] = true;
        document.getElementById("myUL").appendChild(li);
      }
      // etc...
    }
    

    【讨论】:

      【解决方案3】:

      使用jQuery.each() 方法遍历id="myUL"parent 内的所有&lt;li&gt; 元素,以检查该值是否存在。

      我添加了一个示例 &lt;ul id="myUL"&gt; 元素来展示它是如何工作的。

      这是改变的功能:

      function newElement() 
      {
        var li = document.createElement("li");
        var inputValue = document.getElementById("myInput").value;
      
        // if empty
        if (inputValue.length == 0)
        {
           alert("You must write something!");
        }
        else
        {
            var exists = false;
      
            // go through all 'li' child elements of parent with id 'myUL'
            $( "#myUL li" ).each(function( index )
            {
                // $( this ).text() is the text of the current 'li' ellement
                var currentLiText = $( this ).text();
                // search for the appended char, the ×
                var doesItContainX = currentLiText.indexOf('\u00D7');
      
               // if an × is found remove it
               if (doesItContainX !== false)
               {
                   currentLiText = currentLiText.substr(0, doesItContainX, currentLiText.length);
               }
      
               // compare the current li value to the inputValue
               // if they are the same, mark that a match was found
               if(currentLiText.toLowerCase() == inputValue.toLowerCase()) exists = true;
          });
      
          // if we didn't find a match add it
          if(!exists)
          {
              document.getElementById("myUL").appendChild(li);
              var t = document.createTextNode(inputValue);
              li.appendChild(t);
          }
          else
          {
              // we found a match report error
              alert('the value already exists');
          }
      }
      

      代码如下:

      (运行底部的sn-p)

      var myNodelist = document.getElementsByTagName("LI");
      var i;
      for (i = 0; i < myNodelist.length; i++) {
        var span = document.createElement("SPAN");
        var txt = document.createTextNode("\u00D7");
        span.className = "close";
        span.appendChild(txt);
        myNodelist[i].appendChild(span);
      }
      
      // Click on a close button to hide the current list item
      var close = document.getElementsByClassName("close");
      var i;
      for (i = 0; i < close.length; i++) {
        close[i].onclick = function() {
          var div = this.parentElement;
          div.style.display = "none";
        }
      }
      
      // Add a "checked" symbol when clicking on a list item
      var list = document.querySelector('ul');
      list.addEventListener('click', function(ev) {
        if (ev.target.tagName === 'LI') {
          ev.target.classList.toggle('checked');
        }
      }, false);
      
      // Create a new list item when clicking on the "Add" button
      function newElement() 
      {
        var li = document.createElement("li");
        var inputValue = document.getElementById("myInput").value;
      
        // if empty
        if (inputValue.length == 0)
        {
           alert("You must write something!");
        }
        else
        {
            var exists = false;
      
            // go through all 'li' child elements of parent with id 'myUL'
            $( "#myUL li" ).each(function( index )
            {
                 // $( this ).text() is the text of the current 'li' ellement
                 var currentLiText = $( this ).text();
                 // search for the appended char, the ×
                 var doesItContainX = currentLiText.indexOf('\u00D7');
                 
                 // if an × is found remove it
                 if (doesItContainX !== false)
                 {
                     currentLiText = currentLiText.substr(0, doesItContainX, currentLiText.length);
                 }
                 
                 // compare the current li value to the inputValue
                 // if they are the same mark that a match was found
                 if(currentLiText.toLowerCase() == inputValue.toLowerCase()) exists = true;
                 // for case-insensitive remove the .toLowerCase()
            });
      
            // if we didn't find a match add it
            if(!exists)
            {
                document.getElementById("myUL").appendChild(li);
                var t = document.createTextNode(inputValue);
                li.appendChild(t);
            }
            else
            {
                // we found a match report error
                alert('the value already exists');
            }
        }
      
        document.getElementById("myInput").value = "";
      
        var span = document.createElement("SPAN");
        var txt = document.createTextNode("\u00D7");
        span.className = "close";
        span.appendChild(txt);
        li.appendChild(span);
      
        for (i = 0; i < close.length; i++)
        {
          close[i].onclick = function()
          {
            var div = this.parentElement;
            div.style.display = "none";
          }
        }
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <ul id="myUL">
        <li>America</li>
        <li>asia</li>
        <li>germany</li>
        <li>Italy</li>
        <li>Canada</li>
      </ul>
      
      <input type="text" id="myInput" value="" />
      
      <input type="button" value="click to add element" onclick="newElement()" />

      【讨论】:

      • 对不起,我的意思是:如果字符串值已存储一次,则不允许它再次存储。一个字符串值不能存储多次
      • 再次道歉,我将发布整个代码供您查看。
      • @V.tharan924 复制我的函数并粘贴它而不是你的函数。它现在应该可以工作了。
      • 我输入两次的值是“America”和“asia”,它们都被添加了两次。感谢您愿意提供帮助以及其他所有人。非常感谢
      • @V.tharan924 现在试试我更新了,并在底部添加了一个 sn-p 以证明它有效。干杯
      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 2011-07-20
      相关资源
      最近更新 更多