How to alert on load in ejs - javascript

I can't seem to make an alert work properly in ejs. Basically I want an alert to appear when the page is loaded and visible but I just can't make it happen. I've dug through Stack and tried different many things with JS and jQuery but all they do is alert before page is visible and I have a blank white screen with an alert and after OK is clicked the page becomes visible. I'm testing it in Opera.
Maybe it's not just scripts and I am missing something?
PS. window.onload function seems to work fine with an ordinary html file but alert shows before some of css is loaded. Just testing. Found it peculiar.
PS. Okay, now it seems really strange. Apparently, the page actually loads but I don't see it refresh. If I refresh the page, I see the alert but the page is blank. But if I minimize the browser and then put it back on, the page is there. What is going on? Video
<%- include('partials/header'); -%>
<body>
<script>
window.onload = () =>{
alert("fully loaded");
}
</script>
<div id="formDiv" class="flexbox-container">
<form action="/addword" method="post" class="ml-auto mr-auto mt-auto mb-auto" id="wordaddFrom" required>
<div class="form-group">
<input type="text" class="form-control" id="wordInput" name="wordInput" placeholder="Word" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="defInput" name="defInput" placeholder="Definition" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="exInput" name="exInput" placeholder="Example" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="defInput" name="titleInput" placeholder="Title" required>
</div>
<div class="form-group">
<select class="form-control" name=genreInput placeholder="Genre">
<option value="" disabled selected hidden>Genre</option>
<option>Games</option>
<option>Movies</option>
<option>Books</option>
</select>
</div>
<ul class="list-inline">
<li class="list-inline-item"><button type="submit" class="btn btn-primary">Submit</button></li>
</ul>
</form>
</div>
</body>
<%- include('partials/footer'); -%>
app.get("/addword", function(req, res) {
res.render("addword");
});
app.post("/addword", function(req, res){
var newWord = new Dicword ({
word: req.body.wordInput,
definition: req.body.defInput,
title: req.body.titleInput,
genre: req.body.genreInput,
example: req.body.exInput
});
Dicword.exists({word: req.body.wordInput}, (function(err, existingDoc){
if (existingDoc === null) {
newWord.save(function(err){
if (!err){
console.log("add succ");
res.render("addwordSUCC");
}
else {console.log(err);}
});
} else {
let exists = "This word already exists"
res.render("addwordFAIL", {exists: exists});
}
}));

The window.onload function only run when the page is loaded and setTimeout function will wait the css is loaded.
You can try
window.onload = () =>{
setTimeout(function() {
alert("fully loaded");
}, 500);
}
or
let everythingLoaded = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(everythingLoaded);
init(); // this is the function that gets called when everything is loaded
}
}, 10);
function init() {
alert('Hello World');
}
or
document.addEventListener('readystatechange', event => {
// When window loaded ( external resources are loaded too- `css`,`src`, etc...)
if (event.target.readyState === "complete") {
init();
}
})
function init() {
alert('Hello World');
}
or In Opera and Safari is same as before but Only change is I nested the alert code in setTimeout function.
document.addEventListener('readystatechange', event => {
// When window loaded ( external resources are loaded too- `css`,`src`, etc...)
if (event.target.readyState === "complete") {
init();
}
})
function init() {
setTimeout(function() {
alert('Hello World');
}, 100);
}
Solution Video

Related

Failed to load resource: net::ERR_FILE_NOT_FOUND in js

"i dont know what the problem is in my code so i need help please. this is the js:"
`const bar = document.getElementById('bar');
const close = document.querySelector('close');
const nav = document.getElementById('navbar');
if (bar) {
bar.addEventListener('click', () => {
nav.classList.add('active');
})
}
if (close) {
close.addEventListener('click', () => {
nav.classList.remove('active');
})
}`
"for the mobile sidebar and here is the html and js for the popup:"
`
</div>
<div class="imgBx">
<img src="C:/Users/Wassim Malas/Downloads/Screenshot_20230128_091355-removebg-preview.png">
</div>
<div class="content">
<div>
<h3>Subscribe!</h3>
<h2>10<sup>%</sup><span>Off</span></h2>
<p>When you subscribe to our newsletter</p>
<div class='form action="https://formsubmit.co/houseofibnsina#outlook.com" method="POST"'>
<input type="hidden" name="_next" value="https://houseofibnsina.com/thanks">
<input type="email" placeholder="Email Address" name="email" required>
<button class="normal" type="submit">Send</button>
</form>
</div>
</div>
</div>
<script>
const popup = document.querySelector('.popup');
const closeit = document.querySelector(".closeit");
window.onload = function(){
setTimeout(function(){
popup.style.display = "block";
}, 1500)
}
closeit.addEventListener('click', () => {
popup.style.display = "none";
})
</script>`
"i am trying to make a popup on my website and have an x in the corner to close it but there is also an x in the mobile version of my website. so when i try to press the x in my mobile version i get this error message <Failed to load resource: net::ERR_FILE_NOT_FOUND> and i dont know why"

JQuery Validator with custom .addMethod over Bootstrap gives problems when was-validated class is active

I'm having some troubles with Bootstrap 5 and JQuery Validator with custom class.
Seems it works separately from Bootstrap.
In this method for checking hex validity (optional) the .was-validated form class generates problems.
jQuery.validator.addMethod("isvalidhex", function(value, element) {
return this.optional(element) || value.match(/^#[a-f0-9]{6}$/i) !== null;
}, "Must be a valid hex");
Here my code
<script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.5/dist/jquery.validate.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.5/dist/additional-methods.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<style>form * { text-align:center; }</style>
<form method="POST" class="needs-validation" id="formAA" novalidate="novalidate">
<div class="mb-3">
<label for="a" class="form-label">A</label>
<input type="text" class="form-control form-control-lg text-center" id="a" name="a" maxlength="100" required="">
</div>
<div class="divdropdowncolor mb-3 text-center">
<label for="selectcolor" class="form-label">B</label><br>
<input class="form-control form-control-lg" type="color" id="selectcolor" name="selectcolor" value="#0AF000" style="display:inline-block; width:48%; vertical-align: middle; float:left;">
<input type="text" class="form-control form-control-lg text-center error" id="selectcolorB" name="selectcolorB" placeholder="#FFFFFF" maxlength="7" style="display:inline-block; width:48%; vertical-align: middle; float:right;" col="7" aria-invalid="true">
</div>
<div class="mb-3" style="clear:both;"></div>
<button type="submit" class="btn btn-primary form-control-lg" style="width:100%;">Submit</button>
</form>
<!-- scripts -->
<script>
function isValidColor(str) { return str.match(/^#[a-f0-9]{6}$/i) !== null; }
$(document).ready(function() {
$('#selectcolorB').val($('#selectcolor').val());
});
$('#selectcolor').on('change', function (event) { $('#selectcolorB').val($('#selectcolor').val()); });
$('#selectcolorB').on('change', function (event) { if( isValidColor($('#selectcolorB').val()) ) { $('#selectcolor').val($('#selectcolorB').val()); } });
</script>
<script>
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
jQuery.validator.addMethod("isvalidhex", function(value, element) {
return this.optional(element) || value.match(/^#[a-f0-9]{6}$/i) !== null;
}, "Must be a valid hex");
$('#formAA').validate({
rules: {
selectcolorB : { isvalidhex : true },
bgcolor : { isvalidhex : true }
},
submitHandler: function(form, e) {
console.log('The form is valid and would have been submitted successfully');
}
});
</script>
<script>
(function () {
'use strict'
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
//form.classList.remove('was-validated')
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
</script>
It's more complicated said than done.
So go use fiddle
https://jsfiddle.net/qmsjo3L7/
Insert in the second input a wrong hex, like (wekdne).
You got the error Must be a valid hex.
If you click over the submit button you can see that the errors are recognized
1) This field is required.
2) Must be a valid hex
but the inputs colors are red for the normal method (input a) and green for the custom method.
Also, if you edit the inputs, the custom method works when the input is changed (keyup or keydown, I don't know) but the normal method works only on submit.
There's someone more able than me that can solve this?
Click on submit
The last <script> block adds an additional submithandler which is causing odd results. Remove that and things immediately improve.
Bootstrap usage is demonstrated at https://github.com/jquery-validation/jquery-validation/blob/master/demo/bootstrap/index-bs4.html, and live demo available at https://jqueryvalidation.org/files/demo/bootstrap/index.html
Implement the errorElement, errorPlacement, highlight and unhighlight directives shown in the above demo and it works as you expect:
https://jsfiddle.net/bytestream/dekzfxns/2/

Google invisible reCaptcha is only working in Incognito mode

I have a Google reCAPTCHA setup on my contact form in my website.
and i'm trying to test it in both localhost and server as well but recaptcha is only working in incognito mode .
without capturing reCAPTCHA mails are sending .
Here my problem is grecaptcha.execute(); is not executing, Please suggest solution for this.
$("#cont_msg").keypress(function (e) {
var key = e.which;
if (key == 13) {
// the enter key code
$("#contact_form_submit").click();
return false;
}
});
$(
".app_form_wrapper .apps_input input, .app_form_wrapper .apps_input textarea"
).keypress(function () {
$(this).parent().removeClass("error");
});
function sendMail() {
var co_name = $("#cont_name").val();
var co_email = $("#cont_email").val();
var co_phone = $("#cont_phone").val();
var co_company = $("#cont_company").val();
var co_message = $("#cont_msg").val();
let data = {
username: co_name,
useremail: co_email,
userphone: co_phone,
usercompany: co_company,
usermessage: co_message,
};
$("#loading").show();
$("#contact_form_submit").hide();
$.ajax({
type: "POST",
url: "contact_ajaxmail.php",
data: data,
success: function (contact) {
//grecaptcha.execute();
$("#loading").hide();
$("#contact_form_submit").show();
var i = contact.split("#");
if (i[0] == "1") {
$("#cont_name").val("");
$("#cont_email").val("");
$("#cont_phone").val("");
$("#cont_company").val("");
$("#cont_msg").val("");
$("#contact_err").html(i[1]);
$(".app_form_wrapper .apps_input").addClass("success");
setTimeout(function () {
$(".app_form_wrapper .apps_input").removeClass("success");
$(".app_form_wrapper .apps_input").removeClass("error");
$("#cont_email").parent().removeClass("error");
}, 2500);
} else {
$("#cont_name").val(data.username);
$("#cont_email").val(data.useremail);
$("#cont_phone").val(data.userphone);
$("#cont_company").val(data.usercompany);
$("#cont_msg").val(data.usermessage);
$("#contact_err").html(i[1]);
$(
".app_form_wrapper .apps_input input, .app_form_wrapper .apps_input textarea"
).each(function () {
if (!$(this).val()) {
$(this).parent().addClass("error");
} else {
if (i[0] == 3) {
$("#cont_email").parent().addClass("error");
} else {
$(this).parent().addClass("error");
}
$(this).parent().removeClass("error");
}
});
}
},
});
}
**My form**
Here iam trying to send mails for entered email
<!DOCTYPE html>
<html lang="en">
<!-- BEGIN HEAD -->
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<form class="app_form_wrapper" role="form" >
<div class="col-lg-6 text-left">
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_name"placeholder="Name">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_email" placeholder="Email">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="tel" class="form-control" id="cont_phone" placeholder="Phone Number" minlength="10" maxlength="15">
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_company" placeholder="Company">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<textarea rows="10" class="form-control" id="cont_msg" placeholder="Message"></textarea>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="g-recaptcha"
data-sitekey="Site_key"
data-callback="sendMail"
data-size="invisible">
</div>
<p>
This site is protected by reCAPTCHA and the Google
Privacy Policy and
Terms of Service apply.
</p>
<a class="btn btn-default btn-lg contact_btn" id="contact_form_submit">Send</a>
<a class="btn btn-default btn-lg contact_btn" id="loading" style="display: none;">Sending...</a>
<p class="input_error"id="contact_err" style="color:#FF6666;position:absolute;font-size:14px;font-weight: 500;letter-spacing: 0.5px;bottom: 10px;left: 0;right: 0;">
</p>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#contact_form_submit").on("click", function () {
var co_name = $("#cont_name").val();
var co_email = $("#cont_email").val();
var co_phone = $("#cont_phone").val();
var co_company = $("#cont_company").val();
var co_message = $("#cont_msg").val();
if (
co_name != "" &&
co_email != "" &&
co_phone != "" &&
co_company != "" &&
co_message != ""
) {
grecaptcha.execute();
} else {
$("#loading").hide();
$("#contact_form_submit").show();
$("#contact_err").html("Please fill all the fields !!!!");
}
});
})
</script>
</body>
</html>
Captcha needs two things to make it work properly
Client side code in Javascript, this you have done by looks of it properly.
Server side code, without implementing server side code the captcha is useless as bots will just post straight to your PHP form without having to enter a captcha! This is your missing piece based on your comments.
See
https://developers.google.com/recaptcha/intro
Notice it says you need to do 2 steps, 1 client side, 2 verify the response:
https://developers.google.com/recaptcha/docs/verify
Google returns loads results but this seems to be an up to date article
https://phppot.com/php/php-contact-form-with-google-recaptcha/
Google implementing google captcha php

How to build a confirmation message in a popup for a website built on .NET Core?

I am trying to implement a confirmation message appearing in a popup when a user clicks on a button on a web page built on .NET Core. Then the user can either accept or cancel that message, if they decline then I need them to stay on the same page.
My code:
<div class="row">
<div class="col-md-12">
#Html.DropDownListFor(m => m.For, Model.Sources, new { #id = "ddl" })
</div>
</div>
<div class="row">
<div class="col-md-12">
<p>
<input type="file" name="csvFile" />
</p>
<p>
<button type="submit" class="btn btn-primary" onclick="DisplayConfirmation()">Upload File</button>
</p>
</div>
</div>
<script type="text/javascript">
function DisplayConfirmation() {
var confirm_value = document.getElementById("ddl");
if (confirm_value.value == " Data") {
if (window.confirm("Do you want default package?")) {
}
}
}
</script>
I have had success using this approach taking the confirmation and putting it in a boolean variable first, skipping 'window':
<script type="text/javascript">
function DisplayConfirmation() {
var confirm_value = document.getElementById("ddl");
if (confirm_value.value == " Data") {
var confirmed = confirm("Do you want default package?");
if (confirmed) {
}
}
}
</script>
If the confirm returns false, just let the function run out and nothing will happen.

Submit form not working when using jQuery

I have a form and when the user clicks submit, I would like the form to hide and a thank you message to appear. Unfortunately with the code I have, it's not working and I can't figure out why. I think it might be something with the jQuery so I'd like to try and re-write this function using vanilla JS, but I'm not sure how.
It is the last part of the function, the if (empty.length), hide form, show thank you message that is causing me problems. Everything else is working fine, so its this function I would like to try and write in JavaScript, or try another way using jquery to make it work. The problem is it doesn't work in my code, but when I open this in a jsfiddle, it doesnt just hide the form it opens a new page and I get an error. I don't want the user to be directed to a new page, I just want the form to close and thank-you message to appear. I am very new to this so I apologize if my code is messy.
UPDATE: I really think the issue here is the jQuery, can I write this in plain JS and would that fix it?
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
})
var $form = $('#signup-form'),
$signupForm = $('.form-show'),
$formReplace = $('#thank-you');
$formReplace.hide();
$form.on('submit', function() {
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if (empty.length <= 0) {
$signupForm.hide();
$formReplace.show();
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click-subscribe">Show / hide form</button>
<div id="subscribe-content">
<div class="subscription-signup">
<div class="subscription-close" id="subscription-close"></div>
<div class="email-signup">
<p class="cat-title subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<div class="subscription-form">
<form id="signup-form" class="form-show" name="signup-form" method="post" action="${URLUtils.url('Newsletter-SubscribeMobile')}">
<div class="form-row salutation header">
<label for="salutation">Title</label>
<div class="chzn-row valid salutation">
<select id="title" name="title" class="chzn-global-select input-select optional required">
<option value="">--</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss</option>
</select>
</div>
</div>
<div class="form-row required">
<label for="firstname">
<span aria-required="true">First Name</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="firstname" type="text" name="firstname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="lastname">
<span aria-required="true">Surname</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="lastname" type="text" name="lastname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="signup-email" style="display:none;">Email</label>
<input class="header-signup-email" type="text" id="signup-email-header" name="signup-email" value="" placeholder="Email" />
</div>
<div class="form-row text-center">
<input type="submit" name="signup-submit" id="signup-submit" class="subscribe-submit" value="Submit" />
</div>
</form>
<div id="thank-you">
<p>Thanks for subscribing!</p>
</div>
</div>
</div>
</div>
</div>
I think some other javascript/jQuery code are making issues to run the codes, for simple solution make your code as plugin and called it like following.
create new js file called validation.js
(function($){
$.fn.validation = function(){
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
var $form = $('#signup-form'), $signupForm = $('.form-show'), $formReplace = $('#thank-you'); $formReplace.hide();
this.on('submit', function(e){
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if(empty.length == 0){
$signupForm.hide();
$formReplace.show();
}
e.preventDefault();
});
};
})(jQuery);
Now, call the validation.js at the head like below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="validation.js"></script>
<script type="text/javascript">
$(function(){
$('#signup-form').validation();
});
</script>

Categories

Resources