JavaScript encode field without spoiling the display

坚强是说给别人听的谎言 提交于 2019-12-24 07:36:10

问题


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


回答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:

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


来源:https://stackoverflow.com/questions/18288968/javascript-encode-field-without-spoiling-the-display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!