6

Bug in IE when you use Javascript to modify a form action, when method = get and...

 2 years ago
source link: https://www.codesd.com/item/bug-in-ie-when-you-use-javascript-to-modify-a-form-action-when-method-get-and-url-contains-a-hash.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Bug in IE when you use Javascript to modify a form action, when method = get and URL contains a hash

advertisements

I'm using Javascript to change a form's URL when you submit the form. If that URL contains a hash string (#), then Internet Explorer ignores it and just submits to the part of the html before that. Firefox and Chrome are fine.

Demonstration:

<script type="text/javascript">
function changeURL() {
    var myform = document.getElementById('myform');

    myform.setAttribute("action", "page2.html#hello"); 

    return false;
}
</script>

<form id="myform" action="page1.html" method="get" onsubmit="changeURL()">
    <input type="submit">
</form>

If I change the method to a "post" then it's fine. If I use a "get", IE lands on page2.html but without the #hello in the URL.

This happens regardless of if I use jquery or only javascript, tried each of the following:

myform.action = "page2.html#hello";

myform.attr("action", "page2.html#hello");

myform.get(0).setAttribute("action", "page2.html#hello");

Any suggestions (assume that I have to keep the method as a 'get', and that I must use a hash in the URL, and that I must use Javascript to change this action dynamically)?


Testing on my own in IE8 reveals that it does insist that the hash (#hello) come after the query string (?foo=bar) in a URL. Sadly, your form doesn't do this for you and there's no way to force it to do so when submitting the form.

Try encoding the hash in the form instead:

<script type="text/javascript">
function changeURL() {
    var hidden = document.createElement('input');
    hidden.setAttribute("type", "hidden");
    hidden.setAttribute("name", "hash");
    hidden.setAttribute("value", "hello");
    var myform = document.getElementById('myform');
    myform.setAttribute("action", "page2.html");
    myform.appendChild(hidden);
    // return false;
}
</script>
<form id="myform" action="page1.html" method="get" onsubmit="changeURL()">
    <input type="submit">
</form>

And at the top of page2.html, extract it back out:

<script type="text/javascript">
var qs = window.location.search.substring(1);
var qsarr = qs.split("&");
for (var i=0; i<qsarr.length; i++) {
    var tarr = qsarr[i].split("=");
    if (tarr[0]==="hash") {
        window.location.hash = tarr[1];
    }
}
</script>


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK