Hi all I have following code: my code
I have 2 inputs and 2 regex for each of them
<input type="text" id="FormField_6_input" placeholder="company name" />
<input type="text" id="FormField_13_input" placeholder="zip code" />
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const found = event.target.value.match(companyRGEX);
const zipRGEX = /^[a-zA-Z0-9]{5,9}$/;
const foundZip = event.target.value.match(zipRGEX);
I need to check
if company name is valid but zip is not valid then disable button and show error message for zip
if zip code is valid but compony name is not valid then disable button and show error message for company name
if both of them is not valid then then disable button and show both error messages
I write my code only for company name with one regex and it was work very well, for example:
function validat(event) {
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const found = event.target.value.match(companyRGEX);
const errorMSG = document.getElementById("errorMSG");
if (button && (found || !event.target.value)) {
button.disabled = false;
errorMSG.style.display = "none";
} else {
button.disabled = true;
errorMSG.style.display = "block";
}
}
But when I try to write multi check something going wrong, please help me to resolve this problem.
here is multicheck code:
function validate(event) {
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const found = event.target.value.match(companyRGEX);
const zipRGEX = /^[a-zA-Z0-9]{5,9}$/;
const foundZip = event.target.value.match(zipRGEX);
if (
button &&
(found || !event.target.value) &&
(foundZip || !event.target.value)
) {
if (button && (found || !event.target.value)) {
button.disabled = true;
zip_errorMSG.style.display = "none";
errorMSG.style.display = "block";
} else if (button && (foundZip || !event.target.value)) {
button.disabled = true;
errorMSG.style.display = "none";
zip_errorMSG.style.display = "block";
} else {
button.disabled = false;
errorMSG.style.display = "none";
zip_errorMSG.style.display = "none";
}
} else {
button.disabled = true;
zip_errorMSG.style.display = "block";
errorMSG.style.display = "block";
}
}
P.S. please don't change html, only change js.
Thank you.
const checkvalue = (value, regex) => !!value.match(regex);
function validateCompanyName(event, source) {
const companyRGEX = /^[a-zA-Z0-9_.+,-]*(?:[a-zA-Z][a-zA-Z0-9_,.+-]*){2,}$/;
const zipRGEX = /^[a-zA-Z0-9]{5,9}$/;
const companyIsCorrect = checkvalue(
companyNameField.value,
companyRGEX
);
const zipIsCorrect = checkvalue(zipPostalCode.value, zipRGEX);
if (button && zipIsCorrect && companyIsCorrect) {
button.disabled = false;
zip_errorMSG.style.display = "none";
errorMSG.style.display = "none";
} else if (button && !zipIsCorrect && companyIsCorrect) {
button.disabled = true;
zip_errorMSG.style.display = "block";
errorMSG.style.display = "none";
} else if (button && zipIsCorrect && !companyIsCorrect) {
button.disabled = true;
zip_errorMSG.style.display = "none";
errorMSG.style.display = "block";
} else {
button.disabled = true;
zip_errorMSG.style.display = "block";
errorMSG.style.display = "block";
}
Related
I want to disable my submit button if all three validation rules below fails otherwise disable false. Any help
<script>
const form = document.getElementById('signup-form');
let name = document.getElementById('name');
let email = document.getElementById('email');
let password = document.getElementById('password');
let button = document.getElementById("signup-button");
form.addEventListener('keyup', (e) => {
e.preventDefault();
checkValidation();
});
function checkValidation() {
let nameValue = name.value.trim();
let emailValue = email.value.trim();
let passwordValue = password.value.trim();
let emailValidate = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if (nameValue == "" || nameValue == null) {
document.getElementById('name-error').style.display = 'block';
document.getElementById('name-error').innerText = "Name Cannot be blank";
} else {
document.getElementById('name-error').style.display = 'none';
}
if (emailValue == "" || emailValue == null) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Email Cannot be blank";
} else if (!emailValidate.test(emailValue)) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Please Enter a Valid email";
} else {
document.getElementById('email-error').style.display = 'none';
}
if (passwordValue == "" || passwordValue == null) {
document.getElementById('password-error').style.display = 'block';
document.getElementById('password-error').innerText = "Password Cannot be blank";
} else {
document.getElementById('password-error').style.display = 'none';
}
}
</script>
Now I want to disable my submit button? How can it be achieved
In that function, initialize a variable, lets say isValid to true.
In the checks, if any check fails, set isValid to false.
And at the bottom of the function, add a condition to enable or disable the Submit button. I'm providing a sample code for your reference.
if (isValid === true) {
// Enable the submit button
}
else {
// Enable the submit button
}
You can add a flag like this:
<script>
const form = document.getElementById('signup-form');
let name = document.getElementById('name');
let email = document.getElementById('email');
let password = document.getElementById('password');
let button = document.getElementById("signup-button");
let error = false;
form.addEventListener('keyup', (e) => {
e.preventDefault();
checkValidation();
});
if(error){
button.setAttribute('disabled', '')
}else{
button.removeAttribute('disabled')
}
function checkValidation() {
let nameValue = name.value.trim();
let emailValue = email.value.trim();
let passwordValue = password.value.trim();
let emailValidate = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if (nameValue == "" || nameValue == null) {
document.getElementById('name-error').style.display = 'block';
document.getElementById('name-error').innerText = "Name Cannot be blank";
error = true;
} else {
document.getElementById('name-error').style.display = 'none';
}
if (emailValue == "" || emailValue == null) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Email Cannot be blank";
error = true;
} else if (!emailValidate.test(emailValue)) {
document.getElementById('email-error').style.display = 'block';
document.getElementById('email-error').innerText = "Please Enter a Valid email";
} else {
document.getElementById('email-error').style.display = 'none';
}
if (passwordValue == "" || passwordValue == null) {
document.getElementById('password-error').style.display = 'block';
document.getElementById('password-error').innerText = "Password Cannot be blank";
error = true;
} else {
document.getElementById('password-error').style.display = 'none';
}
}
</script>
I am creating rock, paper, scissors game. And after the battle I want the result to be displaying on the screen for 5 seconds then start counting backwards from 5. Both functions should start one after another but I don't know how to do it. I tried different variations using setTimeout() but apparently I am missing something. I did my research before asking the question but couldn't find anything helpful.
JS:
let elements = [
"../img/scissors.png",
"../img/rock.png",
"../img/paper.png",
];
const startBtn = document.querySelector('.start')
const startImg = document.querySelector('.all-elements')
const rules = document.querySelector('.rules')
const phase1 = document.querySelector('.phase-1')
const phase2 = document.querySelector('.phase-2')
const imgs = document.querySelectorAll('.wrapper img')
const opponent = document.querySelector('.opponent-choise')
const result = document.querySelector('.result')
let clicked = false
let time = 5
startBtn.addEventListener('click', ()=>{
phase1.style.display = "none"
phase2.style.display = "block"
})
for(let i = 0; i < imgs.length; i++){
let me = imgs[i]
me.addEventListener('click', ()=>{
if(clicked == false){
clicked = true
chooseSign(me, imgs)
countDown()
}
})
}
function chooseSign(b, c){
c.forEach((a)=>{
a.style.display = "none"
})
b.style.display = "block"
b.style.cursor = "auto"
displayOpponent()
checkForWinner(b, opponent)
}
function displayOpponent(){
let random = Math.floor(Math.random() * 3)
opponent.style.display = "block"
opponent.src = elements[random]
}
function checkForWinner(me, opponent){
let meSrc = me.getAttribute('src')
let opponentSrc = opponent.getAttribute('src')
if(me.src == opponent.src){
let a = "Draw!"
showWinner(a)
} else if
(meSrc == elements[0] && opponentSrc == elements[2] ||
meSrc == elements[1] && opponentSrc == elements[0] ||
meSrc == elements[2] && opponentSrc == elements[1])
{
let a = "You win!"
showWinner(a)
} else {
let a = "You lose!"
showWinner(a)
}
}
function showWinner(a){
result.textContent = a
setTimeout('showWinner()', 5000)
}
function countDown(){
result.textContent = time
time--
if(time == -1){
return
}
setTimeout('countDown()', 1000)
result.textContent = time
}
In case someone is wondering I solved the problem. Here is the code for the ones who need the answer. Sorry if I haven't provided the answer in the most optimal way.
JS:
let elements = [
"../img/scissors.png",
"../img/rock.png",
"../img/paper.png",
];
const startBtn = document.querySelector('.start')
const exitBtn = document.querySelector('.exit')
const startImg = document.querySelector('.all-elements')
const rules = document.querySelector('.rules')
const phase1 = document.querySelector('.phase-1')
const phase2 = document.querySelector('.phase-2')
const imgs = document.querySelectorAll('.wrapper img')
const opponent = document.querySelector('.opponent-choise')
const result = document.querySelector('.result')
let clicked = false
let time = 4 //put one more second to start on time
let refreshedTime = time
let a
startBtn.addEventListener('click', ()=>{
phase1.style.display = "none"
phase2.style.display = "block"
result.textContent = "Choose a sign!"
})
exitBtn.addEventListener('click', ()=>{
if(clicked == false){
phase1.style.display = "block"
phase2.style.display = "none"
}
})
for(let i = 0; i < imgs.length; i++){
let me = imgs[i]
me.addEventListener('click', ()=>{
setTimeout(()=>{
if(clicked == false){
clicked = true
time = refreshedTime
chooseSign(me, imgs)
setTimeout(countDown, 2000)
}
}, 1000)
})
}
function chooseSign(b, c){
c.forEach((a)=>{
a.style.display = "none"
})
b.style.display = "block"
b.style.cursor = "auto"
displayOpponent()
checkForWinner(b, opponent)
}
function displayOpponent(){
let random = Math.floor(Math.random() * 3)
opponent.style.display = "block"
opponent.src = elements[random]
}
function checkForWinner(me, opponent){
let meSrc = me.getAttribute('src')
let opponentSrc = opponent.getAttribute('src')
if(me.src == opponent.src){
a = "Draw!"
result.style.color = "yellow"
} else if
(meSrc == elements[0] && opponentSrc == elements[2] ||
meSrc == elements[1] && opponentSrc == elements[0] ||
meSrc == elements[2] && opponentSrc == elements[1])
{
a = "You win!"
result.style.color = "green"
} else {
a = "You lose!"
result.style.color = "red"
}
showWinner(a)
}
function showWinner(a){
result.textContent = a
}
function countDown(){
result.style.color = "black"
time--
if(time == -1){
clicked = false
imgs.forEach((img)=>{
img.style.display = "block"
img.style.cursor = "pointer"
})
opponent.style.display = "none"
result.textContent = "Choose a sign!"
return
}
setTimeout('countDown()', 1000)
result.textContent = time
}
Javascript setTimeout() function is asynchronous in order not to freeze all the js code during the delayed time interval. As you have not provided a minimal reproducible example, I could only guess what you intended. Here is the modified code:
let elements = [
"../img/scissors.png",
"../img/rock.png",
"../img/paper.png",
];
const imgs = document.querySelectorAll('.wrapper img')
const startBtn = document.querySelector('.start')
const startImg = document.querySelector('.all-elements')
const rules = document.querySelector('.rules')
const phase1 = document.querySelector('.phase-1')
const phase2 = document.querySelector('.phase-2')
const opponent = document.querySelector('.opponent-choise')
const result = document.querySelector('.result')
let clicked = false
let time = 5
startBtn.addEventListener('click', ()=>{
phase1.style.display = "none"
phase2.style.display = "block"
})
for(let i = 0; i < imgs.length; i++){
let me = imgs[i]
me.addEventListener('click', ()=>{
if(clicked == false){
clicked = true
chooseSign(me, imgs)
}
})
}
function chooseSign(b, c){
c.forEach((a)=>{
a.style.display = "none"
})
b.style.display = "block"
b.style.cursor = "auto"
displayOpponent()
checkForWinner(b, opponent)
}
function displayOpponent(){
let random = Math.floor(Math.random() * 3)
opponent.style.display = "block"
opponent.src = elements[random]
}
function checkForWinner(me, opponent){
let meSrc = me.getAttribute('src')
let opponentSrc = opponent.getAttribute('src')
if(me.src == opponent.src){
let a = "Draw!"
showWinner(a)
} else if
(meSrc == elements[0] && opponentSrc == elements[2] ||
meSrc == elements[1] && opponentSrc == elements[0] ||
meSrc == elements[2] && opponentSrc == elements[1])
{
let a = "You win!"
setTimeout(showWinner(a), 5000);
} else {
let a = "You lose!"
setTimeout(showWinner(a), 5000);
}
}
function showWinner(a){
result.textContent = a;
setTimeout(countDown(), 5000);
}
function countDown(){
result.textContent = time
time--
if(time == -1){
return
}
result.textContent = time
}
Please provide a minimal reproducible example (i.e. include your relevant html/css) in case there are any further problems.
Not in jQuery, vanilla JS.
I have the below code I'm using that works fine within the console; the problem is the 'goCheck' element does not appear right away at default, after the user crawls through a few sections, then it appears visible; because of this the event listener is hitting null immediately.
How could I get this to execute WHEN my 'goCheck' element becomes visible on page?
var goCheck = document.getElementById('input_52_65_chosen');
goCheck.addEventListener('click', function (event) {
var value1 = document.getElementById('input_52_22').value;
var value2 = document.getElementById('input_52_100').value;
var value3 = document.getElementById('input_52_95').value;
// var value4 = document.getElementById('input_52_96').value;
if (value1 > 0 ) {
document.getElementById('rate').style.display = "none";
document.getElementById('pay-plans').style.display = "none";
document.getElementById('field_52_116').style.display = "none";
} else if (value1 === 0 ) {
document.getElementById('field_52_116').style.display = "block";
}
if (value2 > 0 ) {
document.getElementById('rate').style.display = "none";
document.getElementById('pay-plans').style.display = "none";
document.getElementById('field_52_116').style.display = "none";
} else if (value2 === 0 ) {
document.getElementById('field_52_116').style.display = "block";
}
if (value3 > 0 ) {
document.getElementById('rate').style.display = "none";
document.getElementById('pay-plans').style.display = "none";
document.getElementById('field_52_116').style.display = "none";
} else if (value3 === 0 ) {
document.getElementById('field_52_116').style.display = "block";
}
if (value1 && value2 && value3 == 0 ) {
document.getElementById('field_52_116').style.display = "block";
}
}
);
Listen to every click everywhere, then check if the element you are looking for was clicked:
document.body.addEventListener("click", function(event){
const goCheck = document.getElementById('input_52_65_chosen');
let el = event.target;
while(el && el !== goCheck) el = el.parentElement;
if(!el) return;
//...
});
var lastid;
function show_submenu(obj) {
var ele = document.getElementById(obj).style;
var elemLastId = document.getElementById(lastid);
if (elemLastId != null) {
elemLastId.style.display = "none";
}
lastid = obj;
if (ele.display == "none") {
ele.display = "block";
} else {
ele.display = "none";
}
}
function toggle_menu(id){
var menu = document.getElementById(id);
if(menu.style.display == 'none')
menu.style.display = 'block';
else
menu.style.display = 'none';
}
Can somebody teach me how to debug this code?
I want to reset the main level when I click the button of menu again.
This javascript form validation is not working in IE8 !!
the form submits while the user inters invalid inputs.
it is working properly in other browsers firefox ,opera, chrome.
can you help me please?
<form method="post" name="form1" id="form1" action="editAction.php" onsubmit="return check_user_info()">
===============================
<script type="text/javascript">
function check_user_info()
{
var proceed = true;
if (checkUserFirstName() == 1)
{
document.getElementById("userFname_msg").style.display = "block";
document.getElementById("userFname_msg1").style.display = "none";
proceed = false;
}
else if (checkUserFirstName() == 11)
{
document.getElementById("userFname_msg1").style.display = "block";
document.getElementById("userFname_msg").style.display = "none";
proceed = false;
}
else
{
document.getElementById("userFname_msg").style.display = "none";
document.getElementById("userFname_msg1").style.display = "none";
}
//-----------------------------
if (checkUserLastName() == 1)
{document.getElementById("userLname_msg").style.display = "block";
document.getElementById("userLname_msg1").style.display = "none";
proceed = false;}
else if (checkUserLastName() == 11)
{document.getElementById("userLname_msg1").style.display = "block";
document.getElementById("userLname_msg").style.display = "none";
proceed = false;}
else{document.getElementById("userLname_msg").style.display = "none";
document.getElementById("userLname_msg1").style.display = "none";
}
//-----------------------------
if (checkMobile() == 1)
{
document.getElementById("mobile_msg").style.display = "block";
proceed = false;
}
else
document.getElementById("mobile_msg").style.display = "none";
//----------------------------------
if (checkPhone() == 1)
{
document.getElementById("phone_msg").style.display = "block";
proceed = false;
}
else
document.getElementById("phone_msg").style.display = "none";
//----------------------------
if (proceed)
{
alert ("your information has been updated successfully ..");
return proceed;
}
else
{
return false;
}
} // End function ...
//----------------------------------------------------
function checkUserFirstName()
{
if (document.getElementById("firstName").value.trim().length == 0)
return 1 ;
else if (!(document.getElementById("firstName").value.match(/^[ \.\-_a-zA-Z]+$/)))
return 11 ;
} // End function ...
//--------------------------------------------------
function checkUserLastName()
{
if (document.getElementById("lastName").value.trim().length == 0)
return 1 ;
else if (!document.getElementById("lastName").value.match(/^[ \.\-_a-zA-Z]+$/))
return 11 ;
} // End function ...
//-------------------------------------------------------------
function checkMobile()
{
if (((document.getElementById("mobile").value.trim().length >0) && (document.getElementById("mobile").value.trim().length != 10))|| (isNaN(document.getElementById("mobile").value)))
return 1 ;
} // end function ...
//----------------------------------------------------------
function checkPhone()
{
if(!document.getElementById("TelephoneNumber").value.match(/^[ \/0-9]*$/))
return 1 ;
} // end function ...
</script>
I'm guessing the problem is probably because of the .trim() method on the strings in your check functions. There isn't a String trim method in older browsers, you'd have to use a polyfill to make sure it's always available, no matter the browser. A good example is:
Trim string in JavaScript?
"".trim || String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
is what I use.