简体   繁体   中英

HTML5 validation from javascript

I can't see the validation popup when I create HTML and add events programmaticaly from javascript. Here is the link to my jsfiddle

http://jsfiddle.net/midnightcoder/sdMQ6/1/

Here is my javascript:

var newInput = document.createElement ("input");
document.body.appendChild (newInput);
newInput.type = "text";
//newInput.required = true;
newInput.Id = "inputId";
var newButton = document.createElement ("input");
document.body.appendChild (newButton);
newButton.type = "button";

newInput.addEventListener ("input", checkValid, false); 

function checkValid(newInput) 
{
 if (newInput.value == "") 
 {
   newInput.setCustomValidity("Write a text");
 } 
  else 
 {
   newInput.setCustomValidity(''); 
 }
}

newButton.onclick = function () 
{
   var newInputValue = newInput.value;
   var newInputAdd = document.createElement("p");
   newInputAdd.innerHTML = newInputValue;
   checkValid (newInputValue);
   document.body.insertBefore (newInputAdd, document.body.childNodes[0]);
   newInput.value = '';
 }

What am I doing wrong?

You're calling checkValid with a value, not a reference to a control to which you could apply .setCustomValidity . You want checkValid(newInput) .

Also, I would not leave a space in the fashion of a (b) , rather, write it as a(b) .

I tried to get the tool tip to trigger for a while, I was even able to read out the validation message into a <div> . However, after doing some more research, it seems that you need to trigger a submit event, which you aren't doing but could do through a <form> .

A related question can be found here:

How to show setCustomValidity message/tooltip without submit event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM