【问题标题】:Show hint with required attribute by clicking通过单击显示带有所需属性的提示
【发布时间】:2013-04-19 17:55:29
【问题描述】:

例如我有一个输入:

<input type="text" id="username" required></input>

我还有一个<button onclick="test_click()"></button>

function test_click(){
    //
    // Here i check user input
    // 
}

如果用户输入错误,我如何在单击按钮后显示错误提示?我需要执行oninvalid 事件,我该怎么做?

谢谢。

【问题讨论】:

  • 试试 $('#input_id').trigger('invalid'),但我建议你尝试使用 jquery.validate 插件。(对不起我的英语)

标签: javascript html required


【解决方案1】:

通常,我会使用隐藏的 dom 元素来提供这种反馈。究竟要使用什么 dom 元素取决于您希望错误提示如何出现。

例如,您可以将<span><img> 直接放在<input> 旁边,并将内容设置为显示错误提示。最初,您希望将此元素的样式设置为包含display: none;,这样它就不会出现。然后在您的test_click() 函数中,您可以将样式更改为display: inline;display: block; 等(根据您选择的元素)。

如果您使用的是 jQuery,它可能看起来像这样:

function test_click(){
   if (error_condition)
   {
      $("#errorElementID").css("display","inline");
   }
}

如果你不使用 jQuery,它可能看起来更像这样:

function test_click(){
   if (error_condition)
   {
      document.GetElementById("errorElementID").style.display = "inline";
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2015-07-11
    相关资源
    最近更新 更多