如何在文本字段长度大于定义的数字时显示警报

时间:2017-02-28 11:24:05

标签: javascript html

我是编程中的新Bie,我正在创建一个代码,通过该代码,我如何限制用户在定义的数字中输入值。

我希望用户输入不超过35个字符或长度的字段值。

这是我的书面守则,但它无效

我使用onkeyup方法



function handleChange() {
    var x = document.getElementById("fname");
    var y = document.getElementById("lname");
    if ((x.value > 35) || (y.value > 35))
    {
      alert("value should less than 35");
    }
  }

<form onkeyup="handleChange()">
    Enter your fname: <input type="text" id="fname">
    Enter your lname: <input type="text" id="lname">
</form>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:4)

您可以使用maxlength属性从HTML中执行此操作。因此您不需要handleChange函数。用户将仅限于设定数量的字符。更多信息:https://www.w3schools.com/tags/att_input_maxlength.asp

img_ply.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub


				mAdView = (AdView) findViewById(R.id.adView);
				mAdView.loadAd(new AdRequest.Builder().build());

				mInterstitial.setAdUnitId(getResources().getString(R.string.admob_intertestial_id));
				mInterstitial.loadAd(new AdRequest.Builder().build());

				mInterstitial.setAdListener(new AdListener() {
					@Override
					public void onAdLoaded() {
						// TODO Auto-generated method stub
						super.onAdLoaded();
						if (mInterstitial.isLoaded()) {
							mInterstitial.show();
							mInterstitial.setAdListener(new AdListener() {
								@Override
								public void onAdClosed() {
									super.onAdClosed();
									finish();

									Intent inttv = new Intent(SingleChannelActivity.this, TvPlay.class);
									inttv.putExtra("url", ChannelUrl);
									startActivity(inttv);
								}
							});
						}else{
							super.onAdLoaded();


						}
					}
				});
			}
		});

或者你想做什么,但添加.length

所以..

<input type="text" id="fname" maxlength="35">
<input type="text" id="lname" maxlength="35">

答案 1 :(得分:3)

<form action="/action_page.php">
  Username: <input onkeydown="handleChange()" id="fname" type="text" name="usrname" maxlength="36"><br>
   Username: <input onkeydown="handleChange()" id="lname" type="text" name="usrname" maxlength="36"><br>
  <input type="submit" value="Submit">
</form>


<script>
function handleChange() {
    var x = document.getElementById("fname").value;
    var y = document.getElementById("lname").value;
    console.log(x);
    if ((x.length > 35) || (y.length > 35))
    {
        alert("value should less than 35");
    }
  }
</script>

答案 2 :(得分:1)

应该是:

if ((x.value.length > 35) || (y.value.length > 35))

答案 3 :(得分:0)

<form onkeyup="handleChange()">
Enter your fname: <input type="text"  maxlength="35" id="fname">
Enter your lname: <input type="text"  maxlength="35" id="lname">
</form>
<script>
function handleChange() {
    var x = document.getElementById("fname");
    var y = document.getElementById("lname");
    if ((x.value.length > 34) || (y.value.length > 34))
    {
        alert("value should less than 35");
    }
  }
</script>