-1

When clicking the enter button on the keyboard I want the data to show but not to reset. But if I input new data and click enter I want it to run still without clicking a reset button.

function myFunction() {
 var x = document.getElementById("myText").value;
 document.getElementById("demo").innerHTML = "$" + (x * '.97').toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
<!DOCTYPE html>
<html>
<head>
 <title></title>
</head>
<body>
 <form>
     <input id="myText" placeholder="$149,995.00" style="width:50%;" type="number"> 
            <button onclick="myFunction()" type="button">Convert</button>
 </form>
        <h1 id="demo"></h1>
</body>
</html>
Jacob Pink
  • 17
  • 2
  • You need to handle the form's `submit` event, not the button click. [More on that](https://stackoverflow.com/questions/3350247/how-to-prevent-form-from-being-submitted). – isherwood Apr 06 '20 at 20:44
  • Would you be able to write it out in code for me? New to coding. @isherwood – Jacob Pink Apr 06 '20 at 20:46
  • This has been answered here: https://stackoverflow.com/questions/895171/prevent-users-from-submitting-a-form-by-hitting-enter – kmoser Apr 06 '20 at 21:14
  • remove the `
    ` element so you just have the input and button.
    – 2pha Apr 06 '20 at 22:01

1 Answers1

1

Use preventDefault function from event not to refresh the page.
By default, whenever a form is submitted, the page is refreshed.
Moreover, by default, any input inside a form tag submits the form with an enter key pressed.

The reason you were not being refreshed with the button is that the form was not being submitted with the button click. But it was with an enter key press event in the input.

Try this

<form>
    <input placeholder="$149,995.00" style="width:50%;" type="number" id="input">
    <input type="submit" value="Convert">
</form>

<div id="demo"></div>
const input = document.querySelector('#input');
const form = document.querySelector('form');

form.addEventListener('submit', (e => {
    e.preventDefault();
    const { value } = input;
    document.getElementById("demo").innerHTML = toDollar(value);
}));

const toDollar = (value) => 
    "$" + (value * '.97').toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

Now, you add a listener to the submit event of the form, so you receive an event object where to call preventDefault and avoid the page refresh.

VRoxa
  • 973
  • 6
  • 25