使用jquery和datalist进行验证

时间:2018-06-04 15:22:11

标签: javascript jquery html validation

我遇到类似这样的问题:Validation with datalist

然而,FelDev的答案是在JavaScript中我需要它在jquery中。 我是jquery的新手,因此,如果有人可以提供帮助,那将是非常有帮助的。

以下是FelDev的回答:

let btn = document.getElementById("btnSend");
let form = document.getElementById("zeForm");
let input = document.getElementById("zeInput");
let msg = document.getElementById("msg");
let allowedValues = ["atown", "btown", "ctown"]; // same values as the options in your datalist


btn.onclick = function() {
  let allGood = false;
  
  allowedValues.forEach(function(elm) {
    if(elm === input.value) {
       allGood = true;
       return;
    }
  })

  if(allGood) {
    msg.innerHTML = "Success!!";
    msg.style.color = "green";
    //form.submit();
  } else {
      msg.innerHTML = "This value is not accepted";
      msg.style.color = "red";
  }
    msg.style.display = "inline";

}
#msg {
  display: none;
}

#btnSend {
  display: block;
  margin-top:1rem;
}
<form id="zeForm">
    <input id="zeInput" type="text" list="typ" name="name" placeholder="gtown" > 
        <datalist id="typ">
          <!-- notice the absence of a <select> here... -->
            <option value="atown">atown</option> 
            <option value="btown">btown</option> 
            <option value="ctown">ctown</option> 
        </datalist> 
    </input>
    <p id="msg"></p>
    <button id="btnSend" type="button">send</button>
  </form>

1 个答案:

答案 0 :(得分:0)

所以你需要翻译吗?

所以这个js的jquery是:

let btn = $("#btnSend");
let form = $("#zeForm");
let input = $("#zeInput");
let msg = $("#msg");
let allowedValues = ["atown", "btown", "ctown"]; // same values as the options in your datalist


btn.on('click' , function() {
    let allGood = false;

    allowedValues.each(function(index, element) {
        if (element === input.value) {
            allGood = true;
            return;
        }
    })

    if (allGood) {
        msg.text("Success!!");
        msg.attr('style',"color:green");
        //form.submit();
    } else {
         msg.text("This value is not accepted";
         msg.attr('style',"color:red");
    }
   msg.attr('style',"display:inline");

});