input一键删除value值

本文介绍了一种在网页表单中实现输入框一键清除功能的方法。通过使用jQuery,当输入框内容发生变化时,会自动添加一个清除按钮,点击该按钮即可清空输入框的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>input一键删除value值</title>
		<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
		<style>
			/*input_box*/
			.input_box {
				width: 640px;
				margin: 20px auto 0 auto;
			}

			.input_box .input_content {
				width: 620px;
				margin: 10px auto 0 auto;
			}

			.input_box .input_content input {
				width: 618px;
				height: 60px;
				text-indent: 20px;
				font-family: "Microsoft YaHei";
				font-size: 24px;
				letter-spacing: 0;
				color: #656565;
				background-color: #f7f7f7;
				font-weight: normal;
				line-height: 60px;
				border-radius: 4px;
				border: 1px solid #cecece;
			}

			.input_box .test {
				display: none;
				width: 620px;
				margin: 10px auto 0 auto;
			}

			.input_box .test span {
				font-family: "Microsoft YaHei";
				font-size: 20px;
				font-weight: normal;
				color: #ff2121;
				line-height: 20px;
			}

			.input_box_mistake {
				background-color: #f6d425;
				padding-top: 10px;
				padding-bottom: 10px;
			}

			.input_box_mistake .test {
				display: block;
			}
		</style>
	</head>
	<body>
		<div class="form_box">
			    <div class="input_box input_box_mistake">
				        <div class="input_content">
					            <input type="text">
					        </div>
				        <div class="test">
					            <span>此处为必填,请输入数据</span>
					        </div>
				    </div>
		</div>

		<script>
			//input加上删除按钮
			var $inputText = $("input[type='text']");
			$inputText.css({
				"width": "560px",
				"padding-right": "60px"
			});
			$inputText.parent().css({
				"position": "relative"
			});
			$inputText.keyup(function() {
				$(this).change();
			});
			$inputText.change(function() {
				if ($(this).val() != "" && $(this).parent().find("span").length <= 0) {
					//            console.log("改变了");
					var $mThis = this;
					$(this).parent().append(
						" <span class='clear_btn' style='display:block;width:60px;height: 60px;background:url(http://www.jq22.com/tp/2e6f628a-258a-46db-827e-06f79ca8e032.png) no-repeat center;position: absolute;top: 0;right:0;'></span>"
						);
					$(".clear_btn").click(function() {
						$(this).parent().find("input").val("");
						$(this).remove()
					});
				} else if ($(this).val() == "" && $(this).parent().find("span").length > 0) {
					$(this).parent().find("span").remove();
				}
			});
		</script>
	</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知 秋~

文章里可以看到打赏码哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值