Home>

Briefly explaining the code below, Ajax works when a search character is entered in the form, and it takes a field that applies to the string entered with partial match
It is to display in the view.
However, it also reacts to full-width spaces and half-width spaces, in which case all the values ​​in the DB are fetched and displayed.

<input type = formplaceholder = "Please enter text" />
<Ul>
     </ul>
$(function () {
    $(document) .on ('keyup', '# tag_form', function (e) {
      e.preventDefault ();
      var input = $.trim ($(this) .val ());
      $.ajax ({
        url: '/ search_tag',
        type: 'GET',
        data: ('keyword =' ​​+ input),
        processData: false,
        contentType: false,
        dataType: 'json'
      })
      .done (function (data) {
        $('# results'). find ('. tags_btn'). remove ();
        $(data) .each (function (i, genres) {
          $('# results'). append ('' + genres.tagname + '');
        });
        appendTag ();
      });
    });
    deleteTag ();
});
#controller
  def search_tag
    @tag = Tag.where ('tagname LIKE (?)', "% # {params [: keyword]}%")
    render json: @tag
  end

.where ('tagname LIKE (?)', "% # {params [: keyword]}%")
I think that the reason is that when I entered a space or backspace in the fuzzy search, it was searched with white space characters.
How is it better to deal with white space?

  • Answer # 1

    For example

    keyword = params [: keyword]
    if/^ [\ s] * $/= ~ keyword # Double-byte space after \ s
      Returns nothing
    else
      @tag = Tag.where ('tagname LIKE (?)', "% # {keyword}%")
      render json: @tag
    end

Related articles