【问题标题】:Disabling a button after certain input in a textbox?在文本框中输入某些内容后禁用按钮?
【发布时间】:2017-12-14 23:49:47
【问题描述】:

如何使这个文本框在输入 @、*、-、_ 等值时禁用 play button

文本框代码/输入框代码:

<input id="nick" class="form-control input-lg no-border spaced" placeholder="Name" maxlength="15">

播放按钮代码: 播放

                  <a id="spectate-btn" onclick="spectate(); return false;" class="click btn btn-warning full-width expand spaced" type="submit">Spectate</a>

【问题讨论】:

标签: javascript html


【解决方案1】:

有几点需要考虑:

1) 这是一个锚点,所以仅仅设置disabled 属性并不能切断它。

2) 你正在使用 Vanilla JavaScript。

这是一个尝试:

var disableKeys = ['@', '*', '-', '_'];
window.onload = setEvent;

function setEvent() {
  var btn = document.getElementById('spectate-btn');
  document.getElementById("nick").onkeyup = function(c) {
    if (disableKeys.includes(c.key)) {
      btn.setAttribute('disabled', 'disabled');
      btn.className += " button-disabled";
    }
  }
}

function spectate() {
	alert("This is working!");
}
.button-disabled {
       pointer-events: none !important;
       cursor: default;
       color:Gray;
}
<input id="nick" class="form-control input-lg no-border spaced" placeholder="Name" maxlength="15">
                  <a id="spectate-btn" href="#" onclick="spectate(); return false;" class="click btn btn-warning full-width expand spaced" type="submit">Spectate</a>

请注意,这会添加一个 css 类来模拟禁用按钮。我还添加了自己的函数来模拟你的观看功能,并显示按钮是真正禁用的。

它的工作方式我将函数挂在文本框的keyup 事件上。每次输入一个字符时,我都会检查它是不是字符(所以复制/粘贴,其他事件是您可能必须处理的特殊情况)。我有一个包含您提到的所有字符的数组。您可以向该数组添加更多字符。

既然你不提,我不处理人物被删除的时候。

【讨论】:

    【解决方案2】:

    应该这样做,我使用正则表达式来定位没有字母,但您可以只指定您想要的字符并用管道( | )分隔它们 因为您使用的是引导程序,所以只需添加disabled,引导程序会为您完成剩下的工作并禁用它

    $('input.form-control').on( 'input', function(el){
      var str = $(this).val();
      // I'm targeting any symbol that is not letter but you can specify 
      // each char that you want,, like this: /@|*|-|+/g
      if( str.match( /[^a-z|A-Z]/g ) != null ) {
        // if match is found disable button
        $('a').attr('disabled', 'disabled') ;
      } else {
        $('a').removeAttr('disabled') ;
      }
    });
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input id="nick" class="form-control input-lg no-border spaced" placeholder="Name" maxlength="15">
    
    <a id="spectate-btn" onclick="spectate(); return false;" class="click btn btn-warning full-width expand spaced" type="submit">Spectate</a>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 2013-03-23
      相关资源
      最近更新 更多