Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add value to input by clicking on another input

I have a problem with my project. What I am trying to do is basically an ATM. But I have a problem with adding a value to an input, by clicking on another input/button like in a real ATM. Can someone explain how it should be done?

Here is my code:

<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>ATM</title>
</head>
<body>
Please enter your pin:
<form action="/script2.js" method="get">
   <input type="password" name="pin" pattern="[0-9]{4}" maxlength="4" id="pin" value="">
   <input type="button" value="1"  onclick="add(this.value)">
   <input type="submit" value="Validate">
</form>



<script src="script.js"></script>
</body>
</html> ```

and JS: 

const pinPassword = document.getElementById('pin').value;

function add(x){
   pinPassword.value = x;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you can do is simply list this function and apply it on all your number buttons

<form action="/script2.js" method="get">
   <input type="password" name="pin" pattern="[0-9]{4}" maxlength="4" id="pin" value="">
   <input class="input-button" type="button" value="1"/>
<input class="input-button" type="button" value="2"/>
<input class="input-button" type="button" value="3"/>
<input class="input-button" type="button" value="4"/>
<input class="input-button" type="button" value="5"/>
<input class="input-button" type="button" value="6"/>
<input class="input-button" type="button" value="7"/>
<input class="input-button" type="button" value="8"/>
<input class="input-button" type="button" value="9"/>
<input class="input-button" type="button" value="0"/>
   <input type="submit" value="Validate">
</form>
 
const pinInputEl = document.getElementById('pin')
const buttonEls = document.querySelectorAll('.input-button') 

const touchToAdd = (buttonEl) => {
  buttonEl.addEventListener('click',()=> {
    pinPassword.value += e.target.value
  })
}

buttonEls.forEach(buttonEl => touchToAdd(buttonEl))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading