最小字符数文本框

时间:2015-06-16 00:50:08

标签: javascript html textinput

我的代码因某种原因而无法工作......它是:

HTML:

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;
}

和javascript:

ID   -   AssemID   -   ItemID  -   ItemQty -  ServiceID   -  ServiceQty
1           1            12          102                        
2           1            62          15                              
3           1                                    3              45
4           2                                    6              90
5           2            23           5 

我尝试使用和不引用第二行,并且两者都不做。当我不引用第二行时,我确保将inpt.value更改为inputValue.length。

2 个答案:

答案 0 :(得分:1)

将警报放在return语句之前。

答案 1 :(得分: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>