Domanda

I want to encode a specific search field before submitting as a $_GET request. What I am doing is to apply encodeURIComponent() function over that field before the form is submitted

$('#frmMainSearch').submit(function() {
    var field = $(this).find('#searchinput');
    field.val(encodeURIComponent(field.val()));
});

the issue is that as soon as the text is encoded, the field displays the encoded text which looks a bit weird. Is there anything I can do to avoid it?

Example: I type Hello & Hello. When I click submit button it turns into something like Hello %26 Hello before the page is refreshed. I want to avoid that.

Any solution?

Thanks

È stato utile?

Soluzione

I recently had to solve this same problem. Here's how I did it:

  1. Create the input field that you want to be user-facing, such as this:

    <input class="really-nice-looking-field" 
           id="search-text-display" 
           placeholder="Search for stuff..." 
           type="text">
    
  2. Notice that with the field that's displayed, the name attribute is specifically omitted. This will keep the search-text-display field out of the submitted form, so you don't have unused parameters coming through.

  3. Create a hidden field, which is what will actually be used for the submit, like so:

    <input id="search-text" name="search_text" type="hidden">
    
  4. Capture the submit event from your form to populate the hidden field before the form is submitted, like so:

    $('#site-search').submit(function() {
        $('#search-text').val(
            encodeURIComponent($('#search-text-display').val())
        );
    });
    

This will leave the input field displayed to your users untouched while your parameters come through escaped, as needed:

    Parameters: {"utf8"=>"✓", "search_text"=>"hello%20%26%20hello"}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top