views:

298

answers:

1

I have an select_tag (rails) that loaded a select value with '/' and '.' character in it.

The select tag's onchange redirects the page (using window.location) using concatenated url with the value of the select tag.

These are the things I tried to isolate the problem.

  • Invokes alert javascript to show the concatenated value.
  • Added urlencode to the value passed.
  • Hard code the urlencode'd value to windows.location (and miraculously, it is working).

Thanks in advance.

+1  A: 

Difficult to say without code (or indeed an actual question!), but in general when you build a URL from a text value, you should be calling encodeURIComponent at the client side, rather than trying to encode it at the server side. eg.

<select id="foo">
    <option value="123./">123./</option>
    <option value="456./">456./</option>
</select>

<script type="text/javascript">
    document.getElementById('foo').onchange= function() {
        var v= this.value;
        location.href= 'http://www.example.com/thing?foo='+encodeURIComponent(v);
    };
</script>

However, neither . nor / are special characters in query parameters, so forgetting to encode them in this case would not actually cause a problem. If we're talking about the path part of a URL then / is special and would have to be encoded:

location.href= 'http://www.example.com/things/'+encodeURIComponent(v)+'/view';

http://www.example.com/things/123.%2F/view

However including %2F in paths tends to be troublesome in both Apache and IIS for various obscure and annoying reasons; it is best avoided.

In any case, select tags that redirect the page are bad news and shouldn't really be used. Apart from requiring JS to work at all, they're inconvenient (no open-in-new-tab, bookmark link, etc.), they break keyboard navigation (because onchange is fired immediately, making it impossible to pick another option) and they break the back button (because when you return to the page, the form values are remembered, so you can't change to the same page forwards again as onchange will not fire).

Select-for-navigation is a discredited technique. Today you might instead try a pop-up-on-click <div> full of simple links instead.

bobince