Javascript, page keeps refreshing after outputting results

前端 未结 3 1453
猫巷女王i
猫巷女王i 2021-01-16 01:14

i have a small problem.

I\'m learning Javascript and I decided to make a currency converter but, my page keeps refreshing after the data is being displayed.

3条回答
  •  长情又很酷
    2021-01-16 02:13

    The form is being submitted, so the page refreshes after that. The fix is to put your listener on the form and have the submit handler call it, then return false so that the form doesn't submit. That way if javascript is disabled, not available or fails to run successfully, the form submits and you can do the conversion at the server.

    A common strategy is to have a form that functions correctly without any script, then add scripting to avoid server calls where possible. To do that, you need to either add name attributes to the form controls or change the ID attributes to name attributes.

    Buttons in a form are type submit by default.

    To "refresh the page" you can just call the form's reset method, and you can pass a reference to the form from its submit handler so:

    e.g. in the HTML:

    ...

    and in the function:

    function output_value(form) {
    
        // var my_currency = document.convertions.currency_to_convert.value;
        var my_currency = form.currency_to_convert.value;
    
        // and so on
        ...
    
        alert("Fatal Error, refresh the page.");
        // reset the form
        form.reset(); 
    
        // stop the form submitting
        return false;
    }    
    

提交回复
热议问题