Appending currency sign to a purchase form in your e-commerce site using plain JavaScript.

Appending currency sign to a purchase form in your e-commerce site using plain JavaScript.

12 March, 2019
Appending currency sign to a purchase form in your e-commerce site using plain JavaScript.

Here is the code snippet on how to append currency sign to a purchase form in your e-commerce site.

For example, you have an input that allows user to put in the amount of money to filter out some certain products at different price range, you might also want to remind the user of the selected currency. But how do you append “$” or “€” to the input? Here is how:

<!DOCTYPE html> <html> <head> <title>e-commerce site</title> <style> .input_container { display: flex; align-items: center; } .input { width: 200px; font-size: 20px; } .mock_input { width: auto; display: inline-block; visibility: hidden; overflow:auto; font-size: 20px; } .icon { position:fixed; display: none; margin-left: 20px; align-items: center; } .icon::after { content: '€' } </style> </head> <body> <div class='input_container'> <input name='price-range' class="input" placeholder="type in the amount" /> <span class="icon" /> </div> <div class="mock_input"></div> <script> (() => { const input = document.querySelector('.input[name="number"]'); const mockInput = document.getElementsByClassName('mock_input')[0]; const icon = document.getElementsByClassName('icon')[0]; const defaultMarginLeft = 20; const overflowSize = 160; input.oninput = function() { mockInput.innerText = input.value; var inputSize = mockInput.clientWidth; if (!input.value || inputSize >= overflowSize) { icon.style.display = 'none'; } else { icon.style.display = 'flex'; icon.style.marginLeft = inputSize + defaultMarginLeft + 'px'; } }; })(); </script> </body> </html>

Put the above into an HTML file you will see the “€” sign is nicely display at your input box such as this one .

How it works?

In order to append “€” to the end of the user’s input form, we need to know the total width of the user’s input text. But currently there’s no way in JavaScript that we can get the width of the user’s input, so we have to create a “div” element, and at the same time transferring what the user is typing to the “div” element by setting the “innerText” as the following:

const input = document.querySelector('.input[name="number"]');
const fakeInput = document.getElementsByClassName('fakeInput')[0];
input.oninput = function(){
fakeInput.innerText = input.value;
const inputWidth =  fakeInput.clientWidth;
}

In this way, we will know the total width of the user’s input, then we can dynamically put the “€” sign right after the “total width” as “margin-left”; You can do the same thing if you are using React by putting it in the “render” method.

Interested in see more articles like this? Follow w3js for more useful content.

Htmlinput widthJavaScript