MikeL5799 MikeL5799 - 22 days ago 7
Javascript Question

Button to clear text and reset search input not working

Ok, so I have a filterable search form that returns certain images in a grid, which works great, it resets when I delete the text in the search input, but when I click the "Clear" button, which should do the same thing as deleting the text, it doesn't work. Here is the HTML and JQuery used:

<form id="live-search" action="" class="styled" method="post" style="margin: 2em 0;">
<div class="form-group">
<input type="text" class="form-control" id="filter" value="" style="width: 80%; float: left;" placeholder="Type to search"/>
<span id="filter-count"></span>
<input type="button" class="clear-btn" value="Clear" style="background: transparent; border: 2px solid #af2332; color: #af2332; padding: 5px 15px; border-radius: 3px; font-size: 18px; height: 34px;">
</div>
</form>


This is the JQuery for the clearing text:

jQuery(document).ready(function(){
jQuery("#filter").keyup(function(){

// Retrieve the input field text and reset the count to zero
var filter = jQuery(this).val(), count = 0;

// Loop through the comment list
jQuery(".watcheroo").each(function(){

jQuery(this).removeClass('active');

// If the list item does not contain the text phrase fade it out
if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {

jQuery(this).fadeOut();

// Show the list item if the phrase matches and increase the count by 1
} else {

jQuery(this).show();
count++;

}

});

// Update the count
var numberItems = count;

});
//clear button remove text
jQuery(".clear-btn").click( function() {
jQuery("#filter").value = "";

});

});


Any help would greatly be appreciated.

Answer

value is a property on a DOMElement, not a jQuery object. Use val('') instead:

jQuery(document).ready(function($) {
    $("#filter").keyup(function() {
        var filter = $(this).val(), 
            count = 0;

        $(".watcheroo").each(function(){
            var $watcheroo = $(this);
            $watcheroo.removeClass('active');

            if ($watcheroo.text().search(new RegExp(filter, "i")) < 0) {
                $watcheroo.fadeOut();
            } else {
                $watcheroo.show();
                count++;
            }
        });
        var numberItems = count;
    });

    $(".clear-btn").click(function() {
        $("#filter").val(''); // <-- note val() here
    });
}); 

Note that I amended your code to alias the instance of jQuery passed in to the document.ready handler. This way you can still use the $ variable safely within the scope of that function.

Comments