0

I have an similar problem like this post: Validation with datalist

However the answer of FelDev is in JavaScript I need it in jquery . I am new to jquery therefore it would be of great help if some can help.

In the following the answer of 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>
billy.farroll
  • 1,903
  • 2
  • 15
  • 23
S.Rüd
  • 1
  • 1

1 Answers1

0

So do you need a translation?

So the jquery of this js is :

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");

});
  • thank you for your answer, however it does not work with the example code, do you now why? – S.Rüd Jun 05 '18 at 12:12
  • now it does nothing -_-, the code (before in javaskript), it give next to the input red or green a message, when it does not or does match the word in the dataliste – S.Rüd Jun 05 '18 at 12:38
  • Do you import jquery in html? @S.Rüd –  Jun 05 '18 at 12:44