gpt4 book ai didi

jquery - 推特 Bootstrap : how to add x on the right for clearing inside input box when user is typing?

转载 作者:行者123 更新时间:2023-12-01 05:49:28 25 4
gpt4 key购买 nike

我有以下搜索字段。我想在右侧添加一个 x 以清除输入搜索字段内的内容。仅当用户输入文本或输入字段中有某些文本时,才应显示 x。我该怎么做?

<div class="form-group search-bg">
<label class="labelfinder">
Finder
</label>
<button class="btn btn-default push-right1" id="openmodalOnfocus" type="submit"><span class="glyphicon glyphicon-search"></span></button>
<label class="sr-only" for="search">Enter search</label>
<input type="search" class="form-control border-left-none" placeholder="Search keyword">

</div>

最佳答案

这是一个包含一些验证检查的小片段(以使其看起来正确):

var button_exists = false;

$('input[type=search]').keyup(function(){
if($(this).val()!="" && button_exists==false){
//this block checks if the user has typed something
//and if the x button doesn't already exist, when the conditions
//are true, the button is created
$(this).before('<span class="input-group-addon"><button type="button" class="close search-clear">&times;</button></span>');
button_exists = true;
}
else if($(this).val()=="" && button_exists==true)
{
//if the user has cleared the input and the button exists,
//it should be removed
$(this).prev('span').remove();
button_exists=false;
}
});

$(document).on('click','button.search-clear',function(){
//when the x button is clicked, clear the input and remove the button
$(this).closest('div').find('input[type=search]').val('');
$(this).closest('span').remove();
button_exists=false;
});

在 HTML 中,您需要将其包装在 .input-group 内:

<div class="input-group">
<input type="search" class="form-control border-left-none" placeholder="Search keyword">
</div>

<强> DEMO

引用:

1) .keyup() - 用户按下并释放按键后检测的事件

2) .on() - 为动态创建的按钮绑定(bind)点击事件

关于jquery - 推特 Bootstrap : how to add x on the right for clearing inside input box when user is typing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23750953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com