Hendra Nucleo Hendra Nucleo - 9 months ago 44
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 class="filter">
<p class="textTrigger">Please choose</p>

Here is the jQuery:

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

var rels = [];
$('.textTrigger').html(rels.join(', '));

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


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

Answer Source
  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 () {
    $('.results > div').show();
    $('.textTrigger').html('Please choose');