检查文本的最小长度并使用JS更改某个<span> </span>

时间:2015-02-21 11:35:44

标签: javascript object

我现在已经设置了这个:

<div class="col-sm-offset-4 col-sm-4">
            <form method="post">
                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon danger"><span class="glyphicon glyphicon-remove"></span></span><input type="text" class="form-control" name="validate-text" id="validate-text" placeholder="Username">

                    </div>
                </div>
            </form>
</div>

enter image description here

我希望用户名前面的te span改为:

<span class="input-group-addon danger"><span class="glyphicon glyphicon-remove"></span></span>

enter image description here

如何让javascript检查此框中的文字并更改范围?

2 个答案:

答案 0 :(得分:3)

  

您必须根据长度修改添加和删除类。   查看下面的示例。当输入长度大于5时,它将   添加课程glyphicon-ok其他glyphicon-remove

$(document).ready(function() {
			$("#username").keyup( function () {
				if($(this).val().length > 5) {
					$("#usernameIcon").removeClass("glyphicon-remove");
					$("#usernameIcon").addClass("glyphicon-ok");
				} else {
					$("#usernameIcon").removeClass("glyphicon-ok");
					$("#usernameIcon").addClass("glyphicon-remove");
				}
			});
		});
<!doctype html>
<html lang="en">

<head>
	<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
	<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
	<div class="col-sm-offset-4 col-sm-4">
	    <form method="post">
	        <div class="form-group">
	            <div class="input-group">
	                <span class="input-group-addon danger"><span id="usernameIcon" class="glyphicon glyphicon-remove"></span></span><input id="username" type="text" class="form-control" name="validate-text" id="validate-text" placeholder="Username">
	            </div>
	        </div>
	    </form>
	</div>	
</body>

</html>

答案 1 :(得分:1)

如果你使用jQuery,这应该给你输入文本的长度:

$('input#validate-text').val().length