Creating captchas seems like a mistake in reasoning to me

I am encountering an issue with my code. I created a basic newbie-level captcha using Javascript. Below is the code snippet:

<!DOCTYPE html>
<html>
<head>
    <style>
    </style>
</head>

<body>
    <h1>Testing captcha</h1>
    <hr> 
    <img id="firstImage" img src="pictureOne.jpg"> 
    <input type="text" id="firstInput"></input>
    <button type="button" onclick="checker()">Confirm</button>
    <hr> 
    <p id="cone">Please type what you see in this picture, This is a captcha to prevent over-spamming</p>
</body>
<script>
    function checker() { 
        var checkPic = document.getElementById('firstImage').src = 'pictureOne.jpg'
        var takePic = document.getElementById('firstInput').value;
        checkPic.toString()
        if (checkPic === "pictureOne" && takePic === 'c' ) { 
            document.getElementById('firstImage').src = 'pictureTwo.jpg';
            alert("Please confirm the second captcha");
        } else if (checkPic === 'pictureTwo.jpg' && takePic === 'u') { 
            alert("Ready to download.")
        }
    }
</script>
</html>


How does the captcha function? It's designed to be simple - after completing the first captcha, the second image will appear, and upon completion of that captcha, a specific task will be displayed. However, there seems to be an error in the code. I'm unsure if it's a problem with my conditional statements or something else entirely. I've been stuck on this for about 7 hours now and would appreciate any assistance.

Answer №1

The code you provided has several issues that need to be addressed for it to work properly.

  1. It is recommended to remove the unused attribute img from

    <img id="firstImage" img src="pictureOne.jpg">

  2. To ensure the correct functionality, remove = 'pictureOne.jpg' from

    var checkPic = document.getElementById('firstImage').src = 'pictureOne.jpg'
    and retrieve the actual content of element #firstImage instead of setting it to 'pictureOne.jpg' every time

  3. There is a line checkPic.toString() that can be removed as it is unnecessary (and also missing a ; at the end)

  4. Use == instead of ===, as === will compare if both sides are the same object, not just equal. For example, if i=5 and x=5, i==x is true but i===x is false and i===i is true

  5. Consider using .endsWith(" to compare image locations, as they begin with http://xyz.abc/ and only the end needs to be checked

<!DOCTYPE html>
<html>
<head>
    <style>
    </style>
</head>

<body>
    <h1>Testing captcha</h1>
    <hr> 
    <img id="firstImage" src="pictureOne.jpg"> 
    <input type="text" id="firstInput"></input>
    <button type="button" onclick="checker()">Confirm</button>
    <hr> 
    <p id="cone">Please type what you see in this picture, This is a captcha to prevent over-spamming</p>
</body>
<script>
    function checker() { 
        var checkPic = document.getElementById('firstImage').src;
        var takePic = document.getElementById('firstInput').value;
        if (checkPic.endsWith("pictureOne.jpg") && takePic == 'c' ) { 
            document.getElementById('firstImage').src = 'pictureTwo.jpg';
            alert("Please confirm the second captcha");
        } else if (checkPic.endsWith('pictureTwo.jpg') && takePic == 'u') { 
            alert("Ready to download.")
        }
    }
</script>
</html>

Let's discuss the CAPTCHA further or has your query been resolved?

Answer №2

Make sure to only use the image filename in your code, rather than the full URL path. To do this, you'll need to extract the substring from the end of the URL.

<!DOCTYPE html>
    <html>
    <head>
        <style>
        </style>
    </head>

    <body>
    <h1>Testing Captcha</h1>
    <hr>
    <img id="firstImage" src="image.jpg">
    <input type="text" id="firstInput"/>
    <button type="button" onclick="checker()">Confirm</button>
    <hr>
    <p id="cone">Please enter the text shown in the image above. This is a captcha feature to prevent spam.</p>
    </body>
    <script>

        function checker() {
            alert(123);
            var checkPic = document.getElementById('firstImage').src;
            var takePic = document.getElementById('firstInput').value;

            checkPic = checkPic.substring(checkPic.lastIndexOf('/')+1);

            if (checkPic === "image.jpg" && takePic === 'c') {
                document.getElementById('firstImage').src = 'new-image.jpg';
                alert("Please confirm the second captcha.");
            } else if (checkPic === 'new-image.jpg' && takePic === 'u') {
                alert("Ready for download.");
            }
        }

    </script>
    </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

Sending a message to a specific client using socket.io

Currently delving into socket.io + node.js, I have mastered sending messages locally and broadcasting using the socket.broadcast.emit() function - where all connected clients receive the message. My next challenge is figuring out how to send a private mes ...

Ways to examine the origin of an image based on the attributes of a React component that I have passed as a prop?

I'm facing an issue where I can't use the component's prop to set the src of an image that I imported from a file path in my component's JavaScript file. I have tried different syntaxes but none seem to be working. Here are the formats ...

Ensure that every route is prefixed with /api

Is there a way to set all routes accepted by Express to start with /api without explicitly defining it? Current: this.app.get('/api/endpoint-A', (req, res) => { return res.send('A'); }); this.app.get('/api/endpoint-B', ...

Can Self-Invoking Functions, Resharper 6.1, and JS Lint all Play Nice Together?

Consider this piece of JavaScript code: MyCompany.MyProduct = {}; (function () { "use strict"; MyCompany.MyProduct.doSomethingAmazing = function () { }; }()); This approach is acceptable and passes Mr Crockford's JavaScript lint. Howe ...

What is the best way to customize a MaterialUI outlined input using a global theme overrides file?

I've been working on customizing my theme file with overrides, and I've encountered a strange bug while trying to style the outlined input. It seems like there are two borders appearing when these styles are implemented. https://i.stack.imgur.co ...

Which option would be more beneficial for crafting a responsive UI: integrating a UI framework with three.js or solely relying on vanilla

In my quest to create a 3D editor using three.js, I find myself in uncharted territory. While I have a good grasp of JavaScript and three.js, my knowledge of web development and UI frameworks is lacking. Mrdoob's editor utilizes plain JavaScript for U ...

Place a vertical slider adjacent to an HTML element on either the left or right side

I'm struggling to bind a range slider to the left or right side of a canvas that displays video. Despite my efforts, CSS seems to be putting up a strong fight. I can handle issues like stretching and slider values, but attaching it to the canvas is pr ...

Bringing in an external .js file into nuxt.config.js

Having trouble importing config.js with the project's API keys and getting undefined as a return value. //config.js var config = { fbAPI: "key" } - //nuxt.config.js const cfg = require('./config') env: { fbAPI: cfg.apiKey } Wonder ...

how can JavaScript be used to retrieve an object based on a condition from an array of objects and an ArrayList

My JavaScript challenge involves working with an array of objects called arrobj and a list called prgList. The goal is to extract the names from arrobj based on the programs listed in prgList. If the program exists in arrobj, it should be displayed accor ...

What is the number of steps jQuery animates in?

Exploring my creative side, I decided to create my own custom animate function. Struggling to achieve a seamless animation effect, unlike the smooth transitions produced by jQuery. I'm curious about the formula they utilize to determine the ideal num ...

The contenteditable div's selectAll feature doesn't function properly when it gains focus

I'm working with divs in a table structure and here's an example: <div contenteditable="true" onfocus="document.execCommand('selectAll',false,null)">Something</div> Clicking on a div to focus works perfectly, selectin ...

What is the best way to keep vue-meta up to date when the route or URL

The issue I am facing is that the meta data on my website does not update when the route changes. Even though the route has a watch function that updates the view correctly, the metaInfo() method from vue-meta fails to keep up with the changes. Below is an ...

Use JQuery to gradually decrease the opacity of divs individually

I am currently working on a function that fades out all divs except the one that has been clicked on simultaneously. However, I want them to fade out one by one instead. Additionally, I would like the divs to fade out in a random order. If anyone knows ho ...

The Ajax post function successfully executes on the first attempt, but on subsequent tries it does

My goal is to send data from a forum asynchronously to a PHP page and display the response in a specific ID without refreshing the page. The first time I submit, everything works perfectly. The text is successfully sent to append.php and the new list of i ...

When attempting to dispatch in getServerSideProps, the State refuses to change. Could it be due to the Redux-Next-Wrapper?

I'm facing an issue where the Redux Store does not change when I dispatch in getServerSideProps. Even though I can see the changes in console log after dispatch, the store appears as an empty array when the page loads. Why are these changes not taking ...

How can AngularJS apps handle authentication?

Seeking input on user authentication with AngularJS and Zend... I currently have Angular on the client side and Zend on the server side handling authentication successfully. However, I'm looking for best practices and code examples for enhancing the ...

Display a text box upon clicking an item

I've been curious about how to create the effect of a text box or div that appears when clicked on, similar to what you see in this. Scroll down and click on "show patchnotes"; I've been puzzled by this for a while but haven't come across a ...

Using TypeScript gives you the ability to specify the type of an object while destructuring it,

Currently in the process of refactoring a NodeJS application to TypeScript. I have been consistently using object destructuring and have also been creating aliases while object destructuring, as shown in the code block below. My question is, how can I sp ...

Summon wicket from the non-wicket-component entity

I am currently utilizing js-lib to transform text into a rich-editor, complete with options such as "bold", "italic" and more. The RichEditor also includes an UploadImage button, for which I am able to modify the call-back function: function startUploadi ...

When developing a node.js project using VMWare's shared folder, how can you manage the node_modules folder?

My current project needs to run on Linux, but I am using a Windows computer. This means I have to use a VM. Despite wanting to use WebStorm, I am avoiding JB Gateway due to its numerous bugs. My solution was to utilize the VMWare share folder function. Ho ...