【问题标题】:Minimum character count text box最小字符数文本框
【发布时间】:2015-08-31 15:50:04
【问题描述】:

我的代码由于某种原因无法正常工作..这里是:

html:

<input type="text" name="post" maxlength="140" />

对于 javascript:

var inpt = document.getElementsByName("post")[0];
// var inputValue=document.getElementById(post).value;
if (inpt.value < 10) {
    return false;
    alert("Post must be longer than 10 characters.");
} else {
return true;
}

我在引用和不引用第二行的情况下都试过了,但都什么都不做。当我取消引用第二行时,我还确保将 inpt.value 更改为 inputValue.length。

【问题讨论】:

  • 应该是:inpt.value.length &lt; 10.
  • @PHPglue 仍然无法正常工作,伙计
  • 您的代码可能在name='post' 元素之前定义。使用onload 来克服这个问题。您应该使用外部 JavaScript 引用 &lt;head&gt; 中脚本标记的 src 属性,并在代码上使用 onload 事件,例如:var pre = onload; onload = function(){ if(pre)pre(); /* run code here */ }

标签: javascript html textinput


【解决方案1】:

有2个问题

var inpt = document.getElementsByName("post")[0];

//need to test the length
if (inpt.value.length < 10) {
    alert("Post must be longer than 10 characters.");
    //return after the alert
    return false;
} else {
    return true;
}

还要确保脚本是在事件上触发的

function validate() {
  var inpt = document.getElementsByName("post")[0];

  //need to test the length
  if (inpt.value.length < 10) {
    alert("Post must be longer than 10 characters.");
    //return after the alert
    return false;
  } else {
    return true;
  }
}
<form onsubmit="return validate()">
  <input type="text" name="post" maxlength="140" />
  <button>Save</button>
</form>

【讨论】:

    【解决方案2】:

    将警报放在返回语句之前。

    【讨论】:

      猜你喜欢
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多