midnightcoder
midnightcoder

Reputation: 5

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?

Upvotes: 0

Views: 128

Answers (2)

Andrew Morton
Andrew Morton

Reputation: 25013

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).

Upvotes: 1

zero298
zero298

Reputation: 26867

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

Upvotes: 0

Related Questions