我有以下搜索字段。我想在右侧添加一个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">×</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>
参考:
1).keyup() -当用户按下并释放键时检测到的事件
2).on() -为动态创建的按钮绑定click事件
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句