Click on an image to select four numbers using JavaScript

I have a selection of images representing numbers 1 through 9. When a user clicks on one of these images, I want to save the corresponding number (e.g., if they click on the image with the number 1, I want to save the number 1). However, I only require four numbers for the password. How can I ensure that the user inputs only four digits into a single variable?

Below is the code I am currently using:

<html>
    <title>My Title</title>
    <head><link rel="stylesheet" type="text/css" href="style.css">
        <script type="text/javascript">
            var selectedNumber;
            function changeImage(number) {
                document.getElementById("img").src = number;
            }
        </script>
    </head>

    <body>
        <div class="login">
          <img src="image/1.png" class="i-1" onclick='number('1')'/>
          <img src="image/2.png" class="i-2" />
          <img src="image/3.png" class="i-3" />
          <img src="image/4.png" class="i-4" />
          <img src="image/5.png" class="i-5" />
          <img src="image/6.png" class="i-6" />
          <img src="image/7.png" class="i-7" />
          <img src="image/8.png" class="i-8" />
          <img src="image/9.png" class="i-9" />
        </div>
    </body>
</html>

Answer №1

Let's dive into an example to kick things off.

<html>
<title>Time</title>

<head>
  <link rel="stylesheet" type="text/css" href="csstime.css">
  <script type="text/javascript">
    var number;
    var code = "";

    function switchImage(a) {
      document.getElementById("img").src = a;
    }

    function enterNumber(v) {
      if (code.length <= 3) {
        code += v;
      } else
        alert('You have already entered 4 digits');
    }
  </script>
</head>

<body>
  <div class="login">
    <img src="img/1.png" class="i-1" onclick="enterNumber('1')" />
    <img src="img/2.png" class="i-2" onclick="enterNumber('2')" />
    <img src="img/3.png" class="i-3" onclick="enterNumber('3')" />
    <img src="img/4.png" class="i-4" onclick="enterNumber('4')" />
    <img src="img/5.png" class="i-5" onclick="enterNumber('5')" />
    <img src="img/6.png" class="i-6" onclick="enterNumber('6')" />
    <img src="img/7.png" class="i-7" onclick="enterNumber('7')" />
    <img src="img/8.png" class="i-8" onclick="enterNumber('8')" />
    <img src="img/9.png" class="i-9" onclick="enterNumber('9')" />
  </div>
</body>

</html>

Answer №2

One effective method is as follows:

var total = 0;
var code = "";

function createNumber(num)
{
  if(total < 4)
  {
    total++;
    code+=""+num;
  }
  else
  {
    alert("Cannot select more");
  }
}

function displayCode()
{
  alert(code);
}
<div class="login">
  <img height="20" width="20" src="http://icdn.pro/images/en/b/l/blue-ball-icone-9872-128.png" class="i-1" onclick='createNumber(1);'/>
  <img height="20" width="20" src="http://icons.iconseeker.com/png/fullsize/play-stop-pause/stop-normal-blue.png" class="i-2" onclick='createNumber(2);'/>
  <img height="20" width="20" src="http://www.teconic.com/graphics/blue_ball.jpg" class="i-3" onclick='createNumber(3);'/>
  <img height="20" width="20" src="https://bellcomputers.nz/imag/alternative.png" class="i-4" onclick='createNumber(4);'/>
  <img height="20" width="20" src="http://www.clker.com/cliparts/G/t/K/e/5/8/blue-stop-md.png" class="i-5" onclick='createNumber(5);'/>
  <img height="20" width="20" src="http://findicons.com/files/icons/1838/tropical_stuff/128/ball.png" class="i-6" onclick='createNumber(6);'/>
</div>

<button onClick="displayCode();">Display Code</button>

This approach tracks the number of image selections and limits it to a maximum of four.

Answer №3

Take a look at this and let me know if it fits what you're searching for (specifically the first two images):

<html>
    <title>Time</title>
    <head><link rel="stylesheet" type="text/css" href="csshora.css">
        <script type="text/javascript">
            var number;
            var pass = '';
            function changeImage(a) {
                document.getElementById("img").src=a;
            }
            function createPass(e){
              if(pass.length>=4){
              }else{
                pass = pass+e;
              }
              console.log(pass);
            }
        </script>
    </head>

    <body>
        <div class="login">
            <img src="img/1.png" class="i-1" onclick='createPass("1")'/>
            <img src="img/2.png" class="i-2" onclick='createPass("2")'/>
            <img src="img/3.png" class="i-3" />
            <img src="img/4.png" class="i-4" />
            <img src="img/5.png" class="i-5" />
            <img src="img/6.png" class="i-6" />
            <img src="img/7.png" class="i-7" />
            <img src="img/8.png" class="i-8" />
            <img src="img/9.png" class="i-9" />
        </div>
    </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What improvements can be made to streamline this code and make it more concise with fewer lines?

Is there a way to shorten this code using a loop or something similar? It would be really helpful if someone could assist me in making the code more concise so that I can easily add additional nth-child elements like nth-child:4, 5. $(document).ready(fun ...

Ways to refresh UI in ReactJS without triggering a specific event

In my React application, I am displaying various pictures and GIFs that users can attach to a post. Currently, each image has an onClick handler which triggers either a modal with different options or deletes the picture if the user holds down the ctrl key ...

Java Script Custom Print Preview: A unique way to showcase your content

Is there a way to create a custom print preview dialog similar to the browser's print preview using Java Script? I am working on a book reader application that requires customization of the print preview dialog for page counting, automatic pagination, ...

The Autoprefixer script crashes with the error message: TypeError - Patterns can only be a string or an array of strings

After successfully installing autoprefixer and postcss-cli, I embarked on setting up a simple build process with NPM scripts using my command prompt and VS code. As someone with only 2 months of coding experience, I was following a tutorial on CSS/SASS top ...

Ways to display the values stored in localStorage in distinct div elements based on certain conditions

https://i.sstatic.net/BG3qd.png In my recent project, I have created a feature where users can input specific values through input fields and have them stored directly in localStorage. These values represent different tasks, such as Task: Work Description ...

Is there a way to efficiently integrate text from a webpage into a "Twitter Share" button automatically?

I have a cool feature on my website - a random quote generator where users can tweet the current quote at the click of a button. I've set up a Twitter share link using jQuery that dynamically updates with each new quote: $('.twitter-share-button ...

Changing the input to uppercase within Vue.js

I am looking to capitalize the input data from the user's full name model and would prefer if it is in Latin letters only. Utilizing Vue.js for Uppercase Conversion <p-input :value="value" @input="$emit('input', $event)&qu ...

"Troubleshooting ways to resolve babel-eslint import/export issues without the need for a configuration

Upon running npm start, I encountered the following error message: Parsing error: 'import' and 'export' may only appear at the top level After investigating this issue, suggestions included updating the eslint configuration file with ...

Conditional rendering with React.js in the DOM

Just starting out with React and encountering an issue with rendering using reactDom: index.js import ReactDOM from 'react-dom'; import A from 'components/A'; import B from 'components/B'; render(<A />, document.getEl ...

What is the process of establishing a connection to a web service using Meteor or Node.js?

Currently working on developing a package that interfaces with a web service (either through nodejs or meteor). The web service will be delivering real-time data, so I am in need of a mechanism like a listener or trigger event that can alert me when new da ...

Tips for creating different CSS print layouts within a single-page application

I am working on a single page application with multiple sections that need to display a list of images on separate pages. I was considering using iframes for this task, but I'm looking for advice from someone who has experience with similar situations ...

Setting up Express routes in a separate file from the main one: a step-by-step

My goal is to organize my routes separately from the main app.js file using the following file structure. I attempted to create a api/user/ post API but encountered a 404 error. Any suggestions on how to resolve this issue with the given file structure? . ...

Issue with connecting JavaScript to HTML button

I am currently working on a 10-second countdown feature for a game using Javascript and HTML. Currently, the code runs upon page load. However, I am facing difficulty in linking it to a button so that it triggers upon clicking. ...

Are Django form widgets like datepicker and tabindex being snubbed?

I have been working on creating a stylish form and managed to find some interesting CSS to enhance it. The form is looking good, however, a couple of fields are not displaying correctly; particularly one that is associated with a choice field as the model ...

Set a specific limit on the length of choices within a datalist

Can you help me with this HTML Code? <style type="text/css"> .select { white-space:pre-wrap; background-color:#FF9; width: 500px; } </style> <input type="text" list="browsers" class="select"/> <datalist id=browsers ...

Trouble encountered while retrieving the data structure in order to obtain the outcome [VueJs]

I am facing an issue while trying to save information from an HTTP request into a structure and then store it in local storage. When I attempt to retrieve the stored item and print a specific value from the structure, it does not work! Here is my code: / ...

What is the best way to change the height of cells within a grid layout?

Enhancing the buttons with a touch of depth using box-shadow resulted in an unexpected outcome - the shadows bleeding through the gaps and causing uneven spacing. https://i.sstatic.net/LYssE.png In an attempt to rectify this issue, I decided to tweak the ...

Encountered an error while trying to install Drivelist: Module 'C:Program Files odejs ode_modules pm ode_modules ode-gypin' not found

My electron project relies on the drivelist dependency. However, when I attempt to run "npm install," I encounter an error indicating that the node-gyp\bin folder is missing. Surprisingly, I do have the node-gyp\bin in my node modules and even in ...

Combining two arrays with identical IDs using Angular or JavaScript - a step-by-step guide

As a newcomer to Angular and JavaScript, I am attempting to combine values with the same ID into one row using concatenation. var array = [{ id: "410", value: "val1" }, { id: "411", value: "val1" ...

How can the required flag be integrated with rules validation in react-hook-form and material-ui (mui) for inputs?

Currently, I have implemented react-hook-forms for handling form functionality and validation in our application. On the other hand, we are utilizing MUI/Material-UI as our component library. One issue that arises is that MUI automatically adds a * to inpu ...