This is my script code for captcha generation :
var allValue = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y', 'Z','1','2','3','4','5','6','7','8','9','0',];
var cVal1 = allValue[Math.floor(Math.random()*allValue.length)];
var cVal2 = allValue[Math.floor(Math.random()*allValue.length)];
var cVal3 = allValue[Math.floor(Math.random()*allValue.length)];
var cVal4 = allValue[Math.floor(Math.random()*allValue.length)];
var cVal5 = allValue[Math.floor(Math.random()*allValue.length)];
var cVal6 = allValue[Math.floor(Math.random()*allValue.length)];
var cValue = cVal1+cVal2+cVal3+cVal4+cVal5+cVal6;
captchaValue.innerHTML = cValue;
thisValue = "";
captcha_code.addEventListener('change',function(){
thisValue = captcha_code.value;
})
submitBtn.addEventListener('click',function(){
if(cValue == thisValue){
alert('Valid');
}else if(captcha_code.value == ""){
alert('Invalid Captcha');
}
})
This is my html code for captcha inside the form :
<label for="exampleInputEmail1" class="form-label">Captcha</label>
<div class="captcha">
<div id="captchaValue"></div>
<input type="text" name="captcha_code" class="form-control" id="captcha_code" placeholder="" />
</div>
<a href="/">New Captcha</a>
How to get a new captcha every time I click on the 'New Captcha' button.
You can disable the reload of the page by setting the href attribute to href="javascript:; Then putting the code that generates the new captcha into a function and calling it every time you click the link. You can create this by using event listener.
var allValue = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y', 'Z','1','2','3','4','5','6','7','8','9','0',];
function newCaptcha() {
var cVal1 = allValue[Math.floor(Math.random() * allValue.length)];
var cVal2 = allValue[Math.floor(Math.random() * allValue.length)];
var cVal3 = allValue[Math.floor(Math.random() * allValue.length)];
var cVal4 = allValue[Math.floor(Math.random() * allValue.length)];
var cVal5 = allValue[Math.floor(Math.random() * allValue.length)];
var cVal6 = allValue[Math.floor(Math.random() * allValue.length)];
var cValue = cVal1 + cVal2 + cVal3 + cVal4 + cVal5 + cVal6;
captchaValue.innerHTML = cValue;
}
newCaptcha();
document.querySelector("#new_captcha").addEventListener("click", newCaptcha);
thisValue = "";
captcha_code.addEventListener("change", function () {
thisValue = captcha_code.value;
});
<label for="exampleInputEmail1" class="form-label">Captcha</label>
<div class="captcha">
<div id="captchaValue"></div>
<input type="text" name="captcha_code" class="form-control" id="captcha_code" placeholder="" />
</div>
<a id="new_captcha" href="javascript:;" >New Captcha</a>