I have the following html page with the button "NewPatients" that I am trying to set up to open up a modal with a form to fill out. I can't seem to get the modal to come up. The "openModal" function in the javascript doesn't seem to be getting called.
cshtml file:
#using PracticeApp.Controllers
#{
ViewBag.Title = "Patients";
}
<script src="#Url.Content("../../Js/PatientFormModal.js")" type="text/javascript"></script>
<div class="title">
<div>
<h1 style="float: left">#ViewBag.Title</h1>
</div>
<div class="rmm" style="float: right; display: inline-block">
<ul>
<li>New Patient</li>
<li>Delete Patient(s)</li>
</ul>
</div>
</div>
<div class="content">
<div id="modal_window">
<div style="text-align: right;"><a id="modal_close" href="#">close <b>X</b></a></div>
<p>Complete the form below to add a new patient:</p>
<form id="add_patient" method="POST" action="#" accept-charset="UTF-8">
<p><label>First Name<strong>*</strong><br>
<input type="text" autofocus required size="48" name="fname" value=""></label></p>
<p><label>Last Name<strong>*</strong><br>
<input type="text" autofocus required size="48" name="lname" value=""></label></p>
<p><label>Birthdate (mm/dd/yyyy)<strong>*</strong><br>
<input type="text" autofocus required size="48" name="bday" value=""></label></p>
<p><label>Practice Name<strong>*</strong><br>
<input type="text" autofocus required size="48" name="location" value=""></label></p>
<p><label>SSN<strong>*</strong><br>
<input type="text" autofocus required size="48" name="ssn" value=""></label></p>
<p><input type="submit" name="feedbackForm" value="Add Patient"></p>
</form>
</div>
</div>
This is the javascript file. PatientFormModal.js:
var checkForm = function (e) {
var dateRegEx = /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/;
var form = (e.target) ? e.target : e.srcElement;
var modal_init = function () {
var wrapper = document.getElementById("content");
var window = document.getElementById("modal_window");
var openModal = function (e) {
alert("Here");
wrapper.className = "overlay";
window.style.marginTop = (-modal_window.offsetHeight) / 2 + "px";
window.style.marginLeft = (-modal_window.offsetWidth) / 2 + "px";
e.preventDefault ? e.preventDefault() : e.returnValue = false;
};
var closeModal = function (e) {
wrapper.className = "";
e.preventDefault ? e.preventDefault() : e.returnValue = false;
};
var clickHandler = function (e) {
if (!e.target) e.target = e.srcElement;
if (e.target.tagName == "DIV") {
if (e.target.id != "modal_window") closeModal(e);
}
};
var keyHandler = function (e) {
if (e.keyCode == 27) closeModal(e);
};
if (document.addEventListener) {
document.getElementById("NewPatient").addEventListener("click", openModal, false);
document.getElementById("modal_close").addEventListener("click", closeModal, false);
document.addEventListener("click", clickHandler, false);
document.addEventListener("keydown", keyHandler, false);
} else {
document.getElementById("NewPatient").attachEvent("onclick", openModal);
document.getElementById("modal_close").attachEvent("onclick", closeModal);
document.attachEvent("onclick", clickHandler);
document.attachEvent("onkeydown", keyHandler);
}
};
if (form.fname.value == "") {
alert("Please enter patient's first name");
form.fname.focus();
e.preventDefault ? e.preventDefault() : e.returnValue = false;
return;
}
if (form.lname.value == "") {
alert("Please enter patient's last name");
form.lname.focus();
e.preventDefault ? e.preventDefault() : e.returnValue = false;
return;
}
if (form.bday.value == "") {
alert("Please enter patient's date of birth");
form.bday.focus();
e.preventDefault ? e.preventDefault() : e.returnValue = false;
return;
}
if (document.add_patient.bday.value.search(dateRegEx)==-1) {
alert("Please enter patient's date of birth in the specified format");
}
if (form.location.value == "") {
alert("Please enter patient's practice name");
form.location.focus();
e.preventDefault ? e.preventDefault() : e.returnValue = false;
return;
}
if (form.ssn.value == "") {
alert("Please enter patient's SSN");
form.ssn.focus();
e.preventDefault ? e.preventDefault() : e.returnValue = false;
return;
}
if (document.addEventListener) {
document.getElementById("add_patient").addEventListener("submit", checkForm, false);
document.addEventListener("DOMContentLoaded", modal_init, false);
} else {
document.getElementById("add_patient").attachEvent("onsubmit", checkForm);
window.attachEvent("onload", modal_init);
}
};
Here is CSS for the modal as well:
.content.overlay:before {
content: " ";
width: 100%;
height: 100%;
position: fixed;
z-index: 100;
top: 0;
left: 0;
background: #000;
background: rgba(0,0,0,0.7);
}
#modal_window {
display: none;
z-index: 200;
position: fixed;
left: 50%;
top: 50%;
width: 360px;
padding: 10px 20px;
background: #fff;
border: 5px solid #999;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
.content.overlay #modal_window {
display: block;
}
Your script loads before the HTML does, therefore the DOM element NewPatient is not yet available -> event doesn't get attached -> click doesn't work.
Call the PatientFormModal.js after the HTML.
EDIT: It also looks your JS doesn't get called, so add checkForm() at the end of you JS file.
Related
I'm trying to make the checkbox behave with the Enter key (when tabbed into) the same way it usually does with the space bar or when clicked. I cooked up a case where the checkbox is indeed being checked, but it then doesn't act like it should, i.e. I want it to display a previously hidden text and disappear itself. How can I achieve this? Adding something like document.getElementById("myCheck").click() doesn't work, though.
document.addEventListener('keydown', (e) => {
if( e.key === "Enter" && e.target.classList.contains('myCheck')){
e.target.checked = !e.target.checked;
}
})
function myFunction() {
var form = document.getElementById("form");
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked === true){
form.style.display = "none";
text.style.display = "block";
} else {
form.style.display = "inline-block";
text.style.display = "none";
}
}
* {
margin: 10px;
padding: 0;
font-size: 50px;
}
input {
width: 30px;
height: 30px;
}
p {
color: red;
text-transform: uppercase;
}
<form class="form" id="form" style="display:inline-block">
<input type="checkbox" class="myCheck" id="myCheck" onclick="myFunction()">
<label for="myCheck">Checkbox</label>
</form>
<p id="text" style="display: none;">checkbox is checked</p>
All you need to do is trigger the click event, that will check the box. If you manually set checked and then trigger click it will undo the manual setting.
document.addEventListener('keydown', (e) => {
if( e.key === "Enter" && e.target.classList.contains('myCheck')){
//e.target.checked = !e.target.checked;
e.target.click()
}
})
function myFunction() {
var form = document.getElementById("form");
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked === true){
form.style.display = "none";
text.style.display = "block";
} else {
form.style.display = "inline-block";
text.style.display = "none";
}
}
* {
margin: 10px;
padding: 0;
font-size: 50px;
}
input {
width: 30px;
height: 30px;
}
p {
color: red;
text-transform: uppercase;
}
<form class="form" id="form" style="display:inline-block">
<input type="checkbox" class="myCheck" id="myCheck" onclick="myFunction()">
<label for="myCheck">Checkbox</label>
</form>
<p id="text" style="display: none;">checkbox is checked</p>
I want to show the error message of required if mandatory fields are left blank. I implement it using the following way but every time the function checkinput() is invoked it adds a new span element due to which "required" message is outputted multiple times. I want the span element to be added once and disappears when user fills in the requirement. Here is my code.
const checkinput=(event)=>{
if(event.target.value===""){
event.target.insertAdjacentHTML('afterend','<span class="text-danger">Required</span>')
}
if(event.target.value!==""){
var child=document.querySelector('span');
child.remove();
}
}
document.getElementById("username").addEventListener('blur',checkinput);
document.getElementById("password").addEventListener('blur',checkinput);
document.getElementById("confirmPassword").addEventListener('blur',checkinput);
Reason why new span element is added each time you have a empty input field is because you are calling insertAdjacentHTML each time and inserting a new span element.
What you should do is add span elements with each input field in the html and initially they should be empty.When you want to validate the input fields, if any of the input is empty, select the span element next to that input element and show the error message in that span element using .textContent property. To clear the error message, you just need to set .textContent of the span element to an empty string.
Following code snippets show different ways of validating form inputs.
Form validation on form submit
Following code snippet validates form inputs when form is submitted.
const form = document.querySelector('form');
const usernameError = document.querySelector('#usernameError');
const passwordError = document.querySelector('#passwordError');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username', usernameError);
const passwordValid = validateField(form, 'password', passwordError);
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
function validateField(form, fieldName, errorEl) {
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
<button>Submit</button>
</form>
Form validation on input focus loose
Following code snippet validates form inputs when any of the input looses focus.
const form = document.querySelector('form');
const inputsContainer = document.getElementById('formInputsContainer');
const submitBtn = document.querySelector('button');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username');
const passwordValid = validateField(form, 'password');
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
submitBtn.addEventListener('focus', () => {
form.requestSubmit();
});
inputsContainer.addEventListener('focusout', (event) => {
validateField(form, event.target.name);
});
function validateField(form, fieldName) {
const errorEl = document.getElementById(`${fieldName}Error`);
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div id="formInputsContainer">
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
</div>
<button>Submit</button>
</form>
Form validation as user types in the input field
Following code snippet validates form input as user types in any input field.
const form = document.querySelector('form');
const inputsContainer = document.getElementById('formInputsContainer');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username');
const passwordValid = validateField(form, 'password');
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
inputsContainer.addEventListener('input', (event) => {
validateField(form, event.target.name);
});
function validateField(form, fieldName) {
const errorEl = document.getElementById(`${fieldName}Error`);
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div id="formInputsContainer">
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
</div>
<button>Submit</button>
</form>
You need something like
if(event.target.value==="" && document.querySelector('span') === null){
event.target.insertAdjacentHTML('afterend','<span class="text-danger">Required</span>')
}
if(event.target.value!==""){
var child=document.querySelector('span');
child.remove();
}
You only want to add a span IF the value is an empty string AND the span hsan't been added yet.
You can use this code which create a span which is add to the DOM with the ID which is based on the form element'sname attribute. And that element can be refered to based on the ID which was attach to it before It's been add to the DOM
const checkinput=(event)=>{
if(event.target.value===""){
let spanId = `input-${event.target.name}`
let span = `<span id="${spanId}" class="text-danger">Required</span>`
setTimeout(() =>{
document.getElementById(spanId).remove();
}, 5000);
event.target.insertAdjacentHTML('afterend',span)
}
}
document.getElementById("username").addEventListener('blur',checkinput);
document.getElementById("password").addEventListener('blur',checkinput);
document.getElementById("confirmPassword").addEventListener('blur',checkinput);
<form>
<input type="text" name="username" id="username"/>
<input type="text" name="password" id="password"/>
<input type="text" name="confirmPassword" id="confirmPassword"/>
</form>
May it help
<style>
.errorMsg {
border: 1px solid red;
}
.err {
color: red;
}
</style>
<form>
<input type="text" name="name" id="name">
<input type="password" name="password" id="password">
<button id="submit" type="submit">Submit</button>
</form>
<script>
let nameTag = document.querySelector('#name');
let passwordTag = document.querySelector('#password');
let submitBtn = document.querySelector('#submit');
nameTag.addEventListener('blur', e => validation(e));
passwordTag.addEventListener('blur', e => validation(e));
function validation(e) {
if (e.target.value == '') {
e.target.classList.add('errorMsg')
submitBtn.setAttribute('disabled', true) // Disable submit that user cannot submit
e.target.insertAdjacentHTML('afterend', `<span class="err ${e.target.id}">It is required</span>`)
// In the above line we are inserting an element with class same as id of input that in the remove we remove a particular error message only
} else {
e.target.classList.remove('errorMsg')
submitBtn.removeAttribute('disabled')
document.querySelector(`.err.${e.target.id}`).remove();
//Here code is saying that the element with if 'err' and 'class same as id of input' if both class present then remove it
}
}
</script>
Adding the class = id that a special error message delete
I am trying to change the display property of some text using JS, upon button click.
I have confirmed that the function is firing and running correctly using debugger, but for some reason, I can't grab the specific element I need to change, and assign it to a variable. I also have jquery set up on the page.
I have tried using the console, and document.getElementById('warning-textID') returns the correct element, but when I try to set it to a variable in console, it returns undefined. Am I missing something super obvious here?
Here is the HTML, function and css.
//adding event listener
$(function() {
document.getElementById("submitdiscount").addEventListener("click", putCookie);
});
// click function
function putCookie() {
var enteredValue = document.getElementById("nameBox").value;
var validParam = "test";
var warning = document.getElementById("warning-textID");
var cookieCreated = false;
if(enteredValue == validParam){
console.log('do the thing')
if(cookieCreated == false && enteredValue == validParam){
warning.innerText = "Please enable cookies";
warning.style.display = "";
return;
} else {
warning.innerText = "Please enter the correct code."
warning.style.display = "";
enteredValue.value = "";
return;
}
}
.warning-text {
color: red; text-align: center;
margin-bottom: 0px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="employee-code-input-wrapper" id="employee-code-input">
<div class="employee-code-input-header">
<h2>Enter the employee code you received via email</h2>
</div>
<div class="search-bar emplyoee-code-input-input-wrapper" >
<input class="emplyoee-code-input-input" type="text" placeholder="Enter Employee Code" code="" id="nameBox" name="pass">
<button class="btn btn--submit-employee-form" value="Submit" id="submitdiscount" type="button">submit</button>
</div>
<h2 class="warning-text" id="warning-textID">
Please enter the correct code.
</h2>
</div>
I fixed some mistakes and it worked.
//adding event listener
$(function() {
document.getElementById("submitdiscount").addEventListener("click", putCookie);
// click function
function putCookie() {
var enteredValue = document.getElementById("nameBox").value;
var validParam = "test";
var warning = document.getElementById("warning-textID");
var cookieCreated = false;
if (enteredValue === validParam) {
console.log('do the thing')
if (cookieCreated == false && enteredValue === validParam) {
warning.innerText = "Please enable cookies";
warning.style.display = "block";
return;
}
} else {
warning.innerText = "Please enter the correct code."
warning.style.display = "block";
enteredValue.value = "";
return;
}
}
});
.warning-text {
color: red;
text-align: center;
margin-bottom: 0px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="employee-code-input-wrapper" id="employee-code-input">
<div class="employee-code-input-header">
<h2>Enter the employee code you received via email</h2>
</div>
<div class="search-bar emplyoee-code-input-input-wrapper">
<input class="emplyoee-code-input-input" type="text" placeholder="Enter Employee Code" code="" id="nameBox" name="pass">
<button class="btn btn--submit-employee-form" value="Submit" id="submitdiscount" type="button">submit</button>
</div>
<h2 class="warning-text" id="warning-textID">
Please enter the correct code.
</h2>
</div>
I'm trying to show an error message in the span tags using jQuery. I can get the form fields to highlight in a red box and green box if input right but the text wont show up. I'm new to coding and been looking on the web for ideas and fixes, I know I'm missing something and it maybe simple but I'm racking my brains on it.
$(document).ready(function() {
// Name can't be blank
$('#name').on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// Email must be an email
$('#email').on('input', function() {
var input = $(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// Message can't be blank
$('#message').keyup(function(event) {
var input = $(this);
var message = $(this).val();
console.log(message);
if (message) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// After Form Submitted Validation
$("#contact_submit button").click(function(event) {
var form_data = $("#contact").serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $("#contact_submit" + form_data[input]['name'], ['email'], ['message']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {
error_element.removeClass("error").addClass("error_show");
error_free = false;
}
else {
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free) {
event.preventDefault();
}
else {
alert('No errors: Form will be submitted');
}
});
});
.error {
display: none;
margin-left: 10px;
}
.error_show {
color: red;
margin-left: 10px;
}
input.invalid,
textarea.invalid {
border: 2px solid red;
}
input.valid,
textarea.valid {
border: 2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section class="body">
<form id="contact" method="post" enctype="multipart/form-data" action="">
<h1 class="title">Contact</h1>
<div>
<label for="name">Your Fullname</label>
<input type="text" id="name" name="name" required placeholder="Your Name">
<span class="error error_show">This field is required</span>
</div>
<div>
<label for="email">Your Full Email</label>
<input name="email" type="email" id="email" required placeholder="Your Email">
<span class="error error_show">This field is required</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="20" rows="5" required placeholder="Message"></textarea>
<span class="error error_show">This field is required</span>
</div>
<div id="contact_submit">
<button type="submit"></button>
</div>
</form>
</section>
I think you might have made it more complicated than it needed to be. See if the below snippet doesn't work the way you expected.
$(document).ready(function() {
$('#name').on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$('#email').on('input', function() {
var input = $(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$('#message').keyup(function(event) {
var input = $(this);
var message = $(this).val();
console.log(message);
if (message) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$("#contact_submit #submit_button").click(function(event) {
$("#name_error").hide();
$("#email_error").hide();
$("#message_error").hide();
var success = true;
if (!$("#name").hasClass("valid")) {
success = false;
$("#name_error").show();
}
if (!$("#email").hasClass("valid")) {
success = false;
$("#email_error").show();
}
if (!$("#message").hasClass("valid")) {
success = false;
$("#message_error").show();
}
if (success === false) {
event.preventDefault();
}
else {
alert('No errors: Form will be submitted');
}
});
});
.error {
display: none;
margin-left: 10px;
}
.error_show {
color: red;
margin-left: 10px;
display: none;
}
input.invalid,
textarea.invalid {
border: 2px solid red;
}
input.valid,
textarea.valid {
border: 2px solid green;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<section class="body">
<form id="contact" method="post" enctype="multipart/form-data" action="">
<h1 class="title">Contact</h1>
<div>
<label for="name">Your Fullname</label>
<input type="text" id="name" name="name" required placeholder="Your Name">
<span id="name_error" class="error_show">This field is required</span>
</div>
<div>
<label for="email">Your Full Email</label>
<input name="email" type="email" id="email" required placeholder="Your Email">
<span id="email_error" class="error_show">This field is required</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="20" rows="5" required placeholder="Message"></textarea>
<span id="message_error" class="error_show">This field is required</span>
</div>
<div id="contact_submit">
<input type="submit" id="submit_button" value="Submit">
</div>
</form>
</section>
</body>
</html>
var element = $("#contact_submit" + form_data[input]['name'], ['email'], ['message']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
I think these lines don't select the right span.
I got to it on logging the error_element:
console.log(error_element);
Here is a JSFIDDLE with a "working" selector.
var error_element=$("#contact div span");
Now you can change the selector that it fits your needs!
HTML code:
<html>
<head>
<title>Registration Form</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/style.css">
<script>
function submitAlbum(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
alert("condition1 is ..."+str1);
alert("condition2 is ..."+str2);
alert("condition3 is ..."+str1 == str2);
if (str1 == str2)
{
//alert("Entered captcha is correct");
}
else{
alert("Entered captcha is wrong");
document.getElementById("txtInput").value="";
return false;
}
var frm=document.getElementById("custRegistration");
frm.action="CustomerinfoServlet?formidentity=doRegistrations";
frm.submit();
}
</script>
</head>
<body style=" background-color:#f9f9f9" onload="DrawCaptcha();">
<div style="width: 100%; background-repeat:no-repeat; margin-top:30px; height:546px; background-image: url('images/mac.png')">
<br/><br/>
<div style="margin: 0 auto; background-color: #ffffff; opacity:0.9; border: 1px solid #D7EBFF; width: 400px; padding: 15px; height: 440px; margin-left: 56%;">
<form class="form" name ="custRegistration" id="custRegistration" onsubmit="return submitAlbum(this)" action="download.jsp" method="post" >
<p class="name">
<label for="name">Name <span style="color:red">*</span>:</label>
<input type="text" name="name" id="name" placeholder="" pattern="[A-Za-z ]{3,20}" required/>
<input type="hidden" id="formidentity" name="formidentity" value="doRegistrations"/>
</p>
<p class="email">
<label for="email">Email Id <span style="color:red">*</span>:</label>
<input type="email" name="email" id="email" pattern="((\w+\.)*\w+)#(\w+\.)+(com|org|net|us|info|biz|co)" required aria-required="true" placeholder="" required/>
</p>
<p class="Captcha" style="margin-top:5%; width: 100%;">
<div style="margin:0 0 0 1%">
<label class="captchalabel" style="width:38%; float: left;"><span style="margin:0 0 0 9%">Enter the text </span> <span style="color:red">*</span>:</label>
<input type="text" name="txtInput" id="txtInput" style="float: left;" required/> </div>
<div style="width: 20%; float: right;">
<input type="text" id="txtCaptcha" style="background-color:#E7EBF5; text-align:center; margin: 19px 104px 0px 0px; width: 120px; border-radius:0px; border:1px solid #ccc; font-weight:bold; font-family:Arial; " />
<input type="image" id="btnrefresh" onclick="DrawCaptcha();" src="images/captcha.png"/>
</div>
</p>
<p class="submit">
<input type="submit" value="Submit" />
</p>
</form>
</div>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.realperson.js"></script>
<script type="text/javascript">
//Created / Generates the captcha function
function DrawCaptcha()
{
var a = Math.floor(Math.random() * 10)+ '';
var b = Math.floor(Math.random() * 10)+ '';
var c = Math.floor(Math.random() * 10)+ '';
var d = Math.floor(Math.random() * 10)+ '';
var e = Math.floor(Math.random() * 10)+ '';
var f = Math.floor(Math.random() * 10)+ '';
var g = Math.floor(Math.random() * 10)+ '';
var code = a + ' ' + b + ' '+ c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
document.getElementById("txtCaptcha").value = code
}
// Remove the spaces from the entered and generated code
function removeSpaces(string)
{
return string.split(' ').join('');
}
</script>
</html>
In this I have an issue. The problem is whenever I enter any text in the captcha textbox and press enter key. Then the captcha code is changing, ie, numbers are refreshing.
Also form is getting submit and getting the message ('captcha is wrong').
Can anyone tell me how to stop form submit when we press enter key after entering captcha in textbox?
Well you could disable the Enter button on the captcha input field using jQuery.
An example being:
$('#txtInput').bind("keypress", function (e) {
if (e.keyCode == 13) return false;
});
Where keyCode == 13 is the Enter key
Update
To add the above code in your file, just copy and paste this into your html:
<script type="text/javascript">
$(document).ready(function(){
$('#txtInput').bind("keypress", function (e) {
if (e.keyCode == 13) return false;
});
});
</script>
You can do this using the following jQuery code:
$('#custRegistration').bind("keyup keypress", function(e) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
return false;
}
});
LOL :)
AS dfsq said in comment:
"Why do you press Enter if you don't want to submit the form?"
But to block sending form with enter on input do this:
$('body').on('keydown', '#chaptcha_input', function(e) {
if(e.which == 13 && !e.shiftKey) {
e.preventDefault();
}
});
Try this
$('#txtInput').on("keyup",function(e){
if(e.keyCode == 13)
return false;
// do your stuff here if not enter key pressed
});