How to display messages like those shown with `required =" true "`

The following code will display a small message balloon next to a blank text box when the submit button is clicked.

<form>
    <input type="text" id="name" required="true">
    <button type="submit">Submit</button>
</form>

      

( violin above )

How can I cause such a ball to be displayed in javascript

? Can I also control the content of my post and its location? jQuery

the answers are ok too.

+3


source to share


1 answer


This message that you see by default when you have the required attribute is browser behavior, and the text, location, and style of the message will change depending on the browser you are using.

Chrome and FireFox will say "Please fill out this form" IE will say "This is a required field"

So, if you want to have a custom message, you can use this JS:

document.getElementById('name').setCustomValidity('Your custom validation message comes here');

      



Here is the updated Fiddle: https://jsfiddle.net/cvr687mL/1/

And here's the jquery script to run validation with jquery:

$('input').blur(function(event) {
    event.target.checkValidity();
}).on('invalid', function(event) {
    setTimeout(function() { $(event.target).focus();}, 50);
});

      

+2


source







All Articles