killereks killereks - 2 months ago 11
Javascript Question

JQuery Searching for elements using dropdown list

I want to make it if you pick something in dropdown list except Condition, it will search all elements for that and show them.

my jquery:

$('#searchbtn').click(function(){
var e = document.getElementById("condition");
var strUser = e.options[e.selectedIndex].value;

$('.item').each(function(){
var itemcondition = $('.condition').html();
if (itemcondition === strUser.toLowerCase()){
$(this).show();
}
if (itemcondition !== strUser.toLowerCase()){
$(this).hide();
}
});

})


my html:

<select id="condition">
<option>Condition</option>
<option value="factory new">Factory New</option>
<option value="minimal wear">Minimal Wear</option>
<option value="field tested">Field Tested</option>
<option value="well worn">Well Worn</option>
<option value="battle scarred">Battle Scarred</option>
</select>


this is how element looks like:

<div class="item" data-keywords="m4a4 howl">
<div class="name">M4A4 Howl</div>
<div class="condition">Factory New</div>
<div class="price">800 000 coins</div>
<button>Buy</button>
</div>

Answer

Here is how you can fix it. Your html attribute and javascript code should be changed. You should give option value with ID/slug of condition of your products -- it shouldn't have space as we will manage this data easier in the next step.

<select id="condition">
    <option>Condition</option>
    <option value="factory-new">Factory New</option>
    <option value="minimal-wear">Minimal Wear</option>
    <option value="field-tested">Field Tested</option>
    <option value="well-worn">Well Worn</option>
    <option value="battle-scarred">Battle Scarred</option>
 </select>

and your products list should classes corresponding your selected option value like this.

<div class="item factory-new field-tested" data-keywords="m4a4 howl">
  <div class="name">M4A4 Howl</div>
  <div class="condition">Factory New</div>
  <div class="price">800 000 coins</div>
  <button>Buy</button>
</div>

And your javascript should be changed almost entirely. It's much easier to understand.

$('#searchbtn').click(function() {
    var $condition = $("#condition");
    var condition = $condition.val();
    $('.item').hide();
    $('.item.' + condition).show();
})

hope it helps.

Comments