I have a brand search. I want an adjustment to the query view to be displayed. In the example image below, I am searching for Meto brand, so I display the search results also under the name Meto. I want to display only the first character, if I search for Meto, it will only show the letter M.
How to do that with javascript?
My Template
<div class="brands-list">
@for ((key, val): brandsByFirstChar) {
<div class='brand-by-alphabet'>
<h3 class='alphabet' id='alpha-@key'>@key</h3>
<div class="row brand-collection-container">
<div class='col-sm-3 brand-collection'><ul>
@for ((i, b): val) {
<li><a href="/search?srp-brandIds=@b.getId()&srp-actionTrigger=BRAND&srp-brandMode=true">@b.getName()</a></li>
@if ((i.index() % 1) == 0) {
</ul>
</div>
<div class='col-sm-3 brand-collection'><ul>
}
}
</ul>
</div>
</div>
</div>
}
</div>
My JS
$(document).on("keypress", "#store-searchText", function (e) {
if (e.which == 13) {
var inputVal = $(this).val();
window.location = location.href.replace(location.search, '') + "?q=" + inputVal
}
});
For a js solution, you could change all h3.alphabet to replace with just the first character.
Using the .text overload with a function callback calls .text with each elements text in turn.
However you will get the FOUC (flash of unstyled content) as the page loads then runs your javascript - this would be best changed server-side (in the template)
$(function() {
$(".brands-list h3.alphabet").text(function(i, txt) {
return txt.substr(0, 1);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="brands-list">
<div class='brand-by-alphabet'>
<h3 class='alphabet'>Bosch</h3>
<div class="row brand-collection-container">
<div class='col-sm-3 brand-collection'>
<ul>
<li>Bosch</li>
</ul>
</div>
</div>
<h3 class='alphabet'>Metro</h3>
<div class="row brand-collection-container">
<div class='col-sm-3 brand-collection'>
<ul>
<li>Metro</li>
</ul>
</div>
</div>
</div>
</div>
Alternatively, if you made an ajax call instead of reloading the page, you could intercept the html and amend it before it's displayed.