sansSpoon
sansSpoon

Reputation: 2185

Stop refresh on form submit when using javascript

I have a simple form inspired by this method for encoding svg files as data uri's.

The form submit is handled by vanilla Javascript and works fine, except that the page get's refreshed on the submit and I have to back to get the result. How can I stop the page refresh?

<body>
<form id="svgUriEncode">
    <textarea rows="4" cols="50" id="svgIn"></textarea>
    <button id="encode">encode</button>
    <textarea rows="4" cols="50" id="svgOut"></textarea>
</form>
<script type="text/javascript">

    var form = document.getElementById("svgUriEncode");

    function encodeOptimizedSVGDataUri(form) {
        var uriPayload = encodeURIComponent(form.svgIn.value) // encode URL-unsafe characters
        .replace(/%0A/g, '') // remove newlines
        .replace(/%20/g, ' ') // put spaces back in
        .replace(/%3D/g, '=') // ditto equals signs
        .replace(/%3A/g, ':') // ditto colons
        .replace(/%2F/g, '/') // ditto slashes
        .replace(/%22/g, "'"); // replace quotes with apostrophes (may break certain SVGs)

        form.svgOut.value = 'data:image/svg+xml,' + uriPayload;
    }


    form.encode.addEventListener("click", function () {
      encodeOptimizedSVGDataUri(form);
    });

</script>

Upvotes: 0

Views: 937

Answers (2)

Roberto Bisello
Roberto Bisello

Reputation: 1235

I'll suggest you to use on "submit" instead of on "click" this way you'll catch all submit event, not only the click on the button, then call preventDefault on the event to avoid page reload ;)

var form = document.getElementById("svgUriEncode");

    function encodeOptimizedSVGDataUri(form) {
        var uriPayload = encodeURIComponent(form.svgIn.value) // encode URL-unsafe characters
        .replace(/%0A/g, '') // remove newlines
        .replace(/%20/g, ' ') // put spaces back in
        .replace(/%3D/g, '=') // ditto equals signs
        .replace(/%3A/g, ':') // ditto colons
        .replace(/%2F/g, '/') // ditto slashes
        .replace(/%22/g, "'"); // replace quotes with apostrophes (may break certain SVGs)

        form.svgOut.value = 'data:image/svg+xml,' + uriPayload;
    }


    form.addEventListener("submit", function (evt) {
      evt.preventDefault();
      encodeOptimizedSVGDataUri(form);
    });
<form id="svgUriEncode">
    <textarea rows="4" cols="50" id="svgIn"></textarea>
    <button type="submit" id="encode">encode</button>
    <textarea rows="4" cols="50" id="svgOut"></textarea>
</form>

Upvotes: 0

Rohit Kumar
Rohit Kumar

Reputation: 1782

Add type ="button"... otherwise it will consider it as type="submit" and hence the page refresh

 <button  type ='button' id="encode">encode</button>

Upvotes: 2

Related Questions