MikeL5799 MikeL5799 - 1 year ago 73
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;">

This is the JQuery for the clearing text:


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

// Loop through the comment list


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


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




// 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 Source

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;

            var $watcheroo = $(this);

            if ($watcheroo.text().search(new RegExp(filter, "i")) < 0) {
            } else {
        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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download