Skip to content Skip to sidebar Skip to footer

Javascript Encode Field Without Spoiling The Display

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 submitte

Solution 1:

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:

    <inputclass="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:

    <inputid="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"}

Post a Comment for "Javascript Encode Field Without Spoiling The Display"