如何显示如'required =“true”`所示的消息(How to display messages like those shown with `required=“true”`)

编程入门 行业动态 更新时间:2024-10-23 08:33:24
如何显示如'required =“true”`所示的消息(How to display messages like those shown with `required=“true”`)

单击提交按钮时,以下代码将在空文本字段旁边显示一个小消息气球。

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

( 上面提琴 )

如何在javascript触发此类气球的显示? 我还可以控制其邮件内容及其显示位置吗? jQuery答案也可以。

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.

最满意答案

当您具有required属性时,您看到的此消息是默认的浏览器的本机行为,消息文本和位置和样式将根据您使用的浏览器而更改。

Chrome和FireFox会说:“请填写此表”IE会说:“这是必填字段”

所以如果你想要一个自定义消息,你可以使用这个JS:

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

这是更新的小提琴: https : //jsfiddle.net/cvr687mL/1/

这里是一个jquery脚本,用于使用jquery触发验证:

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

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

Here is the updated Fiddle: https://jsfiddle.net/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); });

更多推荐

display,显示,type,text,submit,电脑培训,计算机培训,IT培训"/> <meta name="d

本文发布于:2023-04-28 03:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1330277.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:所示   消息   true   required   messages

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!