Hendra Nucleo Hendra Nucleo - 24 days ago 7
Javascript Question

jquery function for showing default text after clear filter results

I have custom filtering jQuery, the function is when the checkbox was checked it showing the rel value from the checkbox on div with class filter.

Meanwhile the div filter has default text write "Please choose".

What I need is when someone chooses the checkbox and then clicks the "Clear all" button it will clear the checked value, but at current state the default text from div filter "Please choose" does not appear again after clearing result.

Here is the Html code:

<div class="check">
<label><input type="checkbox" rel="A" name="A"/>a</label>
<label><input type="checkbox" rel="B" name="B"/>b</label>
<label><input type="checkbox" rel="C" name="C"/>c</label>
<label><input type="checkbox" rel="D" name="D"/>d</label>
<button class="clear -filter"onclick="$('input:checkbox').removeAttr('checked');
$('.results > div').show();
$('.textTrigger').html('');" type="reset" value="Clear all">Clear all</button>
</div>

<div class="filter">
<p class="textTrigger">Please choose</p>
</div>


Here is the jQuery:

$('div.check').delegate('input[type="checkbox"]', 'change', function()
{
var $lis = $('.results > div'),
$checked = $('input:checked');

var rels = [];
$checked.each(function()
{
rels.push($(this).attr('name'));
});
$('.textTrigger').html(rels.join(', '));

if ($checked.length)
{
var selector = $checked.map(function()
{
return '.' + $(this).attr('rel');
}).get().join('');

$lis.hide().filter(selector).show();
}
else
{
$lis.show();
}
});


And this is the link to fiddle http://jsfiddle.net/nucleo1985/LugPX/

Answer
  1. Get rid of the onclick attribute on the button, it's not clean code. You're already using jQuery so I suggest you stick to that and move the JS logic away from inside the DOM element
  2. Also use the $.fn.on function instead of delegate

And use this ..

$('button').on('click', function () {
    $('input:checkbox').removeAttr('checked');
    $('.results > div').show();
    $('.textTrigger').html('Please choose');
});

JSFIDDLE