Reputation: 3127
Want to make a search bar in Bootstrap 3 with both the clear glypicon that only appears if there is text, AND the search glypicon that the user clicks to start their search.
I am close:
However, as you can see the x glyph occupies the same space as the search bar. If I try to just position the x farther to the left, it disappears behind the search bar.
My code is below:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.resources>
<xp:styleSheet href="/cc_CommonSearchBar.css" />
</xp:this.resources>
<div class="input-group" style="width:300px">
<!-- <div class="btn-group">-->
<input id="ccSearchInput" type="text" class="form-control"
placeholder="Search for..." />
<span id="ccSearchClear" class="glyphicon glyphicon-remove-circle" />
<span class="input-group-addon" id="basic-addon2">
<i class="glyphicon glyphicon-search" />
</span>
</div>
<xp:scriptBlock id="scriptBlock1">
<xp:this.value><![CDATA[$(document).ready(function(){
$("#ccSearchInput").keyup(function(){
$("#ccSearchClear").toggle(Boolean(this.value));
});
$("#ccSearchClear").toggle(Boolean($("#ccSearchInput").val()));
$("#ccSearchClear").click(function(){
$("#ccSearchInput").val("").focus();
$("#ccSearchClear").hide();
});
});]]></xp:this.value>
</xp:scriptBlock>
</xp:view>
And my CSS:
#ccSearchInput {
width: 200px;
}
#ccSearchClear {
position:absolute !important;
right:5px !important;
top:0 !important;
bottom:0 !important;
height:14px !important;
margin:auto !important;
font-size:14px !important;
cursor:pointer !important;
color:#ccc !important;;
}
Upvotes: 2
Views: 1501
Reputation: 14031
I structured your HTML and JavaScript differently (positive note: reduces your CSS)
Let me know if this works ;)
$(document).ready(function() {
if ($("#ccSearchInput").val() === '') {
$("#clearBtn").hide();
}
$("#ccSearchInput").on('keyup', function() {
if ($(this).val() !== '') {
$("#clearBtn").show();
} else {
$("#clearBtn").hide();
}
});
$("#clearBtn").click(function() {
$("#ccSearchInput").val('').focus();
$(this).hide();
});
});
#basic-addon2:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<hr/>
<div class="row" style="float:right">
<div class="col-xs-4">
<div class="input-group">
<input type="text" class="form-control" id="ccSearchInput" placeholder="Search for...">
<div class="input-group-addon" id="clearBtn"><i class="glyphicon glyphicon-remove-circle"></i>
</div>
<div class="input-group-addon" id="searchBtn"><i class="glyphicon glyphicon-search"></i>
</div>
</div>
<!-- <span class="" id="ccSearchClear"></span> -->
</div>
</div>
Upvotes: 5