最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to display messages like those shown with `required="true"` - Stack Overflow

programmeradmin1浏览0评论

The following code will display a little message balloon beside an empty text field when the submit button is clicked.

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

(fiddle for above)

How can I trigger the display of such a balloon in javascript? Can I also control its message content and its display location? jQuery answers are OK, too.

The following code will display a little message balloon beside an empty text field when the submit button is clicked.

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

(fiddle for above)

How can I trigger the display of such a balloon in javascript? Can I also control its message content and its display location? jQuery answers are OK, too.

Share Improve this question edited Apr 22, 2015 at 19:57 Pedro Lobito 99.2k35 gold badges272 silver badges278 bronze badges asked Apr 22, 2015 at 19:54 Jonathan MJonathan M 17.5k9 gold badges60 silver badges94 bronze badges 9
  • You can just display a tooltip, but you will have to use Javascript. – Nandan Bhat Commented Apr 22, 2015 at 19:58
  • You just need to decide what you want to trigger the balloon... leaving the field, a submit button, or some other event. Then create a tooltip, or animation to run when said event happens. – StephenCollins Commented Apr 22, 2015 at 19:59
  • Downvoter, please tell me why this is a bad question, and your suggestion for improvement. – Jonathan M Commented Apr 22, 2015 at 19:59
  • Are you using the jquery.validate library? (not downvoter) – Travis J Commented Apr 22, 2015 at 20:00
  • 1 @TravisJ, understood, but it was valuable. It should be reposted even if modified for additional content. We don't want to let our rules get in the way of getting answers. – Jonathan M Commented Apr 22, 2015 at 20:10
 |  Show 4 more ments

1 Answer 1

Reset to default 3

This message that you see be default when you have required attribute is browsers's native behavior and the message text and location and style will change based on the browser that you use.

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 es here');

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

And here a jquery script to trigger the validation using jquery:

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

评论列表(0)

  1. 暂无评论