Blur event happens before datepicker fills the field - javascript

I made a minimal example to demonstrate the problem. Reading some questions/answers here on SO, I added
onSelect: function() {
date_input.blur();
},
to the datepicker, although this is still not working for me. Any idea why?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="styles/custom.css">
<link id="bsdp-css" href="https://uxsolutions.github.io/bootstrap-datepicker/bootstrap-datepicker/css/bootstrap-datepicker3.min.css" rel="stylesheet">
<!-- jQuery -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Bootstrap Date-Picker Plugin -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<script type = "text/javascript">
<!--
function validate() {
if( document.invia_dati.nome.value == "" ) {
alert( "Please provide your name!" );
document.invia_dati.nome.focus() ;
return false;
}
}
function validate_field(field_id, error_id) {
var field = document.getElementById(field_id);
var perror = document.getElementById(error_id);
if (field.value === "") {
perror.style.display = "block";
field.style.borderColor = "red"
field.style.boxShadow = "1px 1px 5px red";
} else {
perror.style.display = "none";
field.style.borderColor = "LightGrey"
field.style.boxShadow = "0px 0px 0px LightGrey";
}
}
//-->
$(document).ready(function(){
var date_input=$('input[name="data_nascita"]'); //our date input has the name "data_nascita"
var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
date_input.datepicker({
format: 'dd/mm/yyyy',
container: container,
todayHighlight: true,
autoclose: true,
orientation: "top",
onSelect: function() {
date_input.blur();
},
})
})
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
<title>test</title>
</head>
<body>
<div class="container">
<form class="form-horizontal" name="invia_dati" onsubmit="return(validate());">
<fieldset>
<!-- Form Name -->
<legend>Invia Dati:</legend>
<div class="form-group">
<label class="col-md-4 control-label" for="data_nascita">Data di Nascita</label>
<div class="col-md-4 date">
<input class="form-control" id="date" name="data_nascita" placeholder="13/11/1995" type="text" onblur="return(validate_field('date', 'dob-errore'));">
<p id="dob-errore"> Questo campo non può essere vuotο</p>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="pob">Luogo di nascita</label>
<div class="col-md-4">
<input id="pob" name="pob" type="text" placeholder="i.e. Roma" class="form-control input-md" onblur="return(validate_field('pob', 'pob-errore'));">
<p id="pob-errore"> Questo campo non può essere vuotο</p>
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-4 control-label" for="binvio"></label>
<div class="col-md-8">
<button id="binvio" name="binvio" type="submit" class="btn btn-success">Invio</button>
<button id="bannulla" name="bannulla" type="reset" class="btn btn-inverse">Annulla</button>
</div>
</div>
</fieldset>
</form>
</body>
</html>

As it is written in the documentation of datepicker events: https://bootstrap-datepicker.readthedocs.io/en/latest/events.html#changedate
You need to listen to the changeDate event!
<!--
function validate() {
if (document.invia_dati.nome.value == "") {
alert("Please provide your name!");
document.invia_dati.nome.focus();
return false;
}
}
function validate_field(field_id, error_id) {
var field = document.getElementById(field_id);
var perror = document.getElementById(error_id);
if (field.value === "") {
perror.style.display = "block";
field.style.borderColor = "red"
field.style.boxShadow = "1px 1px 5px red";
} else {
perror.style.display = "none";
field.style.borderColor = "LightGrey"
field.style.boxShadow = "0px 0px 0px LightGrey";
}
}
//-->
$(document).ready(function() {
var date_input = $('input[name="data_nascita"]'); //our date input has the name "data_nascita"
var container = $('.bootstrap-iso form').length > 0 ? $('.bootstrap-iso form').parent() : "body";
date_input.datepicker({
format: 'dd/mm/yyyy',
container: container,
todayHighlight: true,
autoclose: true,
orientation: "top"
})
date_input.on('changeDate', function(e) {
date_input.blur()
})
})
https://bootstrap-datepicker.readthedocs.io/en/latest/events.html#changedate
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="styles/custom.css">
<link id="bsdp-css" href="https://uxsolutions.github.io/bootstrap-datepicker/bootstrap-datepicker/css/bootstrap-datepicker3.min.css" rel="stylesheet">
<!-- jQuery -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Bootstrap Date-Picker Plugin -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css" />
<title>test</title>
</head>
<body>
<div class="container">
<form class="form-horizontal" name="invia_dati" onsubmit="return(validate());">
<fieldset>
<!-- Form Name -->
<legend>Invia Dati:</legend>
<div class="form-group">
<label class="col-md-4 control-label" for="data_nascita">Data di Nascita</label>
<div class="col-md-4 date">
<input class="form-control" id="date" name="data_nascita" placeholder="13/11/1995" type="text" onblur="return(validate_field('date', 'dob-errore'));">
<p id="dob-errore"> Questo campo non può essere vuotο</p>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="pob">Luogo di nascita</label>
<div class="col-md-4">
<input id="pob" name="pob" type="text" placeholder="i.e. Roma" class="form-control input-md" onblur="return(validate_field('pob', 'pob-errore'));">
<p id="pob-errore"> Questo campo non può essere vuotο</p>
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-4 control-label" for="binvio"></label>
<div class="col-md-8">
<button id="binvio" name="binvio" type="submit" class="btn btn-success">Invio</button>
<button id="bannulla" name="bannulla" type="reset" class="btn btn-inverse">Annulla</button>
</div>
</div>
</fieldset>
</form>
</body>
</html>

You can change this event from,
onblur="return(validate_field('date', 'dob-errore'));"
To, onchange="return(validate_field('date', 'dob-errore'));"
Maybe your issue is only with date picker right?

Related

JQuery TODO list, remove list removing everything

I am trying to implement a small todo list with vanilla javascript, but whenever I try to remove something it just removes everything below it as well. But the same function works find for other operations like change and checkbox. Can someone explain what's happening and what can be the fix?
$(function() {
let counter = 0
$('body').css('background-color', localStorage.getItem('theme'))
if (localStorage.getItem('theme') == 'black') {
$('.header').addClass('header-dark')
$('#checkTheme').attr('Checked', 'checked')
}
$('#checkTheme').click(function() {
if ($(this).is(':checked')) {
$('body').css('background-color', 'black')
localStorage.setItem('theme', 'black')
$('.header').addClass('header-dark')
$('#checkTheme').attr('Checked', 'checked')
} else {
$('body').css('background-color', 'rgb(245, 239, 249)')
localStorage.setItem('theme', 'rgb(245, 239, 249)')
$('.header').removeClass('header-dark')
}
})
let paginating = () => {
$('.my-pagination-container').remove()
$('.output').paginathing({
perPage: 3,
firstLast: false,
activeClass: 'my-active',
ulClass: 'my-pagination',
containerClass: 'my-pagination-container'
})
}
$(`.first-input`).keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
addingNewItems()
}
event.stopPropagation();
});
$('.addBtn').on('click', function() {
addingNewItems()
});
let addingNewItems = () => {
counter++
if ($('#input').val() != '') {
appendText()
}
$('#input').val('')
function appendText() {
var onePunct = `<div class='one-item' style='order: ${counter};'>
<div class='display-changable' style='display:flex;align-items: center;justify-content:space-between;'>
<div class='form-check d-flex align-items-center'>
<div>
<input type="checkbox" class='form-check-input checkbox' id="flexCheckDefault${counter}">
</div>
<div>
<label class='form-check-label text-to-do' for="flexCheckDefault${counter}">${$('#input').val()}</label>
</div>
</div>
<div class='d-flex justify-content-center align-items-center'>
<button type="button" class="btn btn-success editBtn">Edit</button>
<div class='trash ps-2'>
<span class="iconify" data-icon="bi:trash-fill"" data-width="29"></span>
</div>
</div>
</div>
<br>
<input type="text" placeholder='${$('#input').val()}' class="form-control editInput display-none" >
<hr>
</div>`;
$(".output").append(onePunct);
if (counter > 3)
paginating()
}
for (let i = 0; i < $('.checkbox').length; i++) {
$(`.checkbox:eq(${i})`).on('change', () => {
$(`.text-to-do:eq(${i})`).wrap('<s/>')
$(`.one-item:eq(${i})`).css('opacity', '0.5')
$(`.checkbox:eq(${i})`).attr('disabled', '')
$(`.editInput:eq(${i})`).removeClass('display-block')
})
$(`.trash:eq(${i})`).on('click', (event) => {
counter++
$(`.one-item:eq(${i})`).remove()
})
$(`.editBtn:eq(${i})`).on('click', () => {
if (!$(`.checkbox:eq(${i})`).attr('disabled')) {
if (!$(`.one-item:eq(${i})`).hasClass('classForCheck')) {
$(`.editInput:eq(${i})`).addClass('display-block');
$(`.one-item:eq(${i})`).addClass('classForCheck')
}
$(`.editInput:eq(${i})`).keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
$(`.text-to-do:eq(${i})`).text($(`.editInput:eq(${i})`).val())
$(`.editInput:eq(${i})`).removeClass('display-block')
$(`.one-item:eq(${i})`).removeClass('classForCheck')
}
event.stopPropagation();
});
}
})
}
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- CSS -->
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.13.1/build/css/alertify.min.css" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<link rel="stylesheet" href="./css/style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<br>
<div class="themes mb-4">
<div>
<span class="iconify" data-icon="fa-solid:sun" data-width="25" style="color: rgb(177, 154, 0);"></span>
</div>
<div class="form-check form-switch success switch-flex">
<input class="form-check-input form-check-input-1" type="checkbox" role="switch" id="checkTheme">
</div>
<div>
<span class="iconify" data-icon="ic:baseline-mode-night" data-width="25" style="color: rgb(174, 154, 23);"></span>
</div>
</div>
<div class="container">
<div class="row">
<div class="col col-md-8 offset-md-2 col-xl-6 offset-xl-3">
<h2 class="header">To do list</h2>
<div class="content card">
<div class="to-do-list d-flex flex-column align-items-center">
<div class="input-group mb-3">
<input id="input" type="text" class="form-control first-input" placeholder="Add New Task" aria-label="Recipient's username" aria-describedby="button-addon2">
<button class="btn btn-outline-secondary addBtn btn-success p-1" type="button" id="button-addon2">
<span class="iconify" data-icon="ant-design:plus-circle-filled" style="color: white;" data-width="30"></span>
</button>
</div>
<div class="output">
<!-- <input type="text" placeholder="" name="" id=""> -->
</div>
</div>
<div class="pagination"></div>
</div>
</div>
</div>
</div>
<script src="./jquery-3.6.0.min.js"></script>
<script src="./paginathing.min.js"></script>
<script src="https://code.iconify.design/2/2.2.1/iconify.min.js"></script>
<script src="./jquery-ui-1.13.2.custom/jquery-ui.min.js"></script>
<script src="./alertifyjs/alertify.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<script src="./js/script.js"></script>
</body>
</html>
Delete function is inside the for loop, whenever you add a new item it goes through the whole list and add event listener to each item.

How can I redirect to another page after verifying the credit card validation?

I need help about redirect another page after credit card valitaditon success.php
Well i dont know anything about vue.
i found something like (onSubmit () {
axios.get('success.php', { )
Something like this? Any help to this poor guy. Thanks :)
Here is vue codes.
<script src="../dist/vue-credit-card-validation.js"></script>
<script type="text/javascript">
const { createApp, ref } = Vue;
const Example = {
computed: {
cardBrandClass(){
return this.getBrandClass(this.cardBrand);
}
},
data() {
return {
cardNumber: null,
cardExpiry: null,
cardCvc: null,
cardPostal: null,
cardErrors: {},
// declaring card-brand in data{} enables card brand name/classes.
cardBrand: null,
}
},
methods: {
validate: function(){
// init
this.cardErrors = {};
// validate card number
if(!this.$cardFormat.validateCardNumber(this.cardNumber)){
this.cardErrors.cardNumber = "Invalid Credit Card Number.";
};
// validate card expiry
if (!this.$cardFormat.validateCardExpiry(this.cardExpiry)) {
this.cardErrors.cardExpiry = "Invalid Expiration Date.";
};
// validate card CVC
if (!this.$cardFormat.validateCardCVC(this.cardCvc)) {
this.cardErrors.cardCvc = "Invalid CVC.";
};
},
reset: function(){
this.cardErrors = {};
this.cardNumber = null;
this.cardExpiry = null;
this.cardCvc = null;
this.cardPostal = null;
this.$refs.cardNumInput.focus();
},
prefill: function(ccNum){
this.cardNumber = ccNum;
this.$cardFormat.setCardType({
currentTarget : this.$refs.cardNumInput,
value: ccNum
});
},
getBrandClass: function (brand) {
let icon = '';
brand = brand || 'unknown';
let cardBrandToClass = {
'visa': 'fab fa-cc-visa',
'mastercard': 'fab fa-cc-mastercard',
'amex': 'fab fa-cc-amex',
'discover': 'fab fa-cc-discover',
'diners': 'fab fa-cc-diners-club',
'jcb': 'fab fa-cc-jcb',
'unknown': 'fa fa-credit-card',
};
if (cardBrandToClass[brand]) {
icon = cardBrandToClass[brand];
};
return icon;
}
},
watch: {
// handle auto-focus to next field
// Note: since CVC can be 3 OR 4 digits we don't watch it
cardNumber: function(val){
if(this.$cardFormat.validateCardNumber(val)){
this.$refs.cardExpInput.focus();
}
},
cardExpiry: function (val) {
if (this.$cardFormat.validateCardExpiry(val)) {
this.$refs.cardCvcInput.focus();
}
}
},
onMounted(){
this.$refs.cardNumInput.focus();
}
};
const app = createApp(Example);
app.use(VueCreditCardValidation);
app.mount('#app');
</script>
Here is html
<!DOCTYPE html>
<html>
<head>
<title>Card validation</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<!-- Libraries only required for demo. -->
<link rel="stylesheet" href="demo.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://unpkg.com/vue#next"></script>
</head>
<body>
<form >
<div class="row pt-4">
<div class="col-sm-12 col-md-6 col-lg-4">
<div class="form-group">
<label>Card Number:</label>
<div class="input-group mb-0">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i :class="cardBrandClass"></i></span>
</div>
<input ref="cardNumInput" :data-error="(cardErrors.cardNumber)?true:false" v-model="cardNumber" type="tel" class="form-control" placeholder="#### #### #### ####" v-cardformat:formatCardNumber>
</div>
<div v-if="cardErrors.cardNumber" class="error">
<small>{{ cardErrors.cardNumber }}</small>
</div>
</div>
</div>
</div>
<div class="row pt-2">
<div class="col-4 col-lg-2">
<div class="form-group">
<label>Card Expiration:</label>
<input ref="cardExpInput" id="card-exp" :data-error="(cardErrors.cardExpiry)?true:false" v-model="cardExpiry" maxlength="10" class="form-control" v-cardformat:formatCardExpiry>
<div v-if="cardErrors.cardExpiry" class="error">
<small>{{ cardErrors.cardExpiry }}</small>
</div>
</div>
</div>
<div class="col-4 col-lg-2">
<div class="form-group">
<label>Card CVC:</label>
<input ref="cardCvcInput" :data-error="(cardErrors.cardCvc)?true:false" v-model="cardCvc" class="form-control" v-cardformat:formatCardCVC>
<div v-if="cardErrors.cardCvc" class="error">
<small>{{ cardErrors.cardCvc }}</small>
</div>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label>Restrict Numeric:</label>
<input placeholder="Only numbers can be entered here..." v-model="cardPostal" class="form-control" v-cardformat:restrictNumeric>
</div>
</div>
</div>
<div class="row">
<div class="col-12 pt-2">
<button type="button" class="btn btn-primary" #click="validate">Validate Card Details</button>
<button type="button" class="btn btn-light" #click="reset">Reset</button>
</div>
</div>
</form>
</body>
</html>
I need help after validation confirm send to success.php page. Thanks.
If you are working with php/html files instead of an single page app, you could simply redirect the user with some basic javascript.
In your method, when you need to redirect the user after validating the card succesfully, just type:
window.location.replace("http://my-url.com/my.page");

Javascript addEventListener doesn't execute

I have a form used to reset a password. On client side I am using vannila js to check if the input is valid however the javascript code doesn't execute completely. It gets the form,password and repeated password id's but it doesn't stop the form from submitting or executing the validation functions.
This is the password reset form. For server side I am using php to check if the proper values exist. If they don't the user can't access the page and the form doesn't exist. However all the data exists so I can see the form
<?php
require_once "../classes/dbh.classes.php";
require_once "../classes/reset-password.class.php";
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!--Bootstrap link -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!--Bootstrap icons link-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.3.0/font/bootstrap-icons.css">
<!--Mapbox css link (optional)-->
<link href='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css' rel='stylesheet'/>
<!--Custom styles link-->
<link rel="stylesheet" href="../CSS/style.css">
<!--JQUERY LINK-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>LP Budgeting - reset password</title>
</head>
<body>
<!--HEADER START-->
<!--navbar start-->
<nav class="navbar navbar-expand-lg bg-black navbar-dark py-3 fixed-top">
<div class="container">
LP<span class="text-warning">Budgeting</span>
<button class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navmenu"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navmenu">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
Home
</li>
</ul>
</div>
</div>
</nav>
<!--navbar end-->
<!--HEADER END-->
<!--RESET PASSWORD FORM START-->
<div class="py-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h5>Reset your password</h5>
<p>Please fill out the fields below and your password will be changed</p>
</div>
<div class="card-body">
<?php
if ($_GET['token'] && $_GET['email']) {
$token = $_GET['token'];
$email = $_GET['email'];
$check_user_class = new reset_password();
if ($check_user_class->check_user_4reset($email, $token)) {
?>
<form method="post" name="reset-form" id="reset-form" action="submit_new_password.php">
<?php
$fullUrl = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (strpos($fullUrl, "error=passwords-mismatch") == true) {
if (isset($_SESSION["password-mismatch"])) {
echo $_SESSION["password-mismatch"];
unset($_SESSION["password-mismatch"]);
}
} elseif (strpos($fullUrl, "error=empty_fields") == true) {
if (isset($_SESSION['empty-passwords'])) {
echo $_SESSION["empty-passwords"];
unset($_SESSION["empty-passwords"]);
}
} else {
if (isset($_SESSION["password-change-success"])) {
echo $_SESSION["password-change-success"];
unset($_SESSION["password-change-success"]);
}
}
?>
<div class="form-group mb-3">
<input type="hidden" name="email" value="<?php echo $email; ?>">
<input type="hidden" name="token" value="<?php echo $token; ?>">
<label for="password">Enter New password</label>
<input type="password" id="password" class="form-control" name='password'
placeholder="New password"><br>
<label for="password2">Repeat your password</label>
<input type="password" id="password2" class="form-control"
name='password_repeat' placeholder="Repeat your password">
</div>
<div class="form-group mb-3">
<input type="submit" id="submit_password" name="submit_password"
class="btn btn-primary">
</div>
</form>
<!--Custom Javascript-->
<script src="../js/password-reset-error-handling.js" type="module"></script>
<!--RESET PASSWORD FORM END-->
<?php
} else {
//That user doesn't exist
echo "error";
}
}
?>
<!--Javascript/Bootstrap links-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
</body>
</html>
The javascript code
const reset_form = document.getElementById('reset-form');
const password = document.getElementById('password');
const password_repeat = document.getElementById('password2');/////////////////all of these variables have the proper value i.e the id of the input fields and the form
reset_form.addEventListener('submit', e => { /////////this is the part that it skips
if (validateInputs()) {
e.currentTarget.submit();
} else {
e.preventDefault();
}
});
function validateInputs() {
//Get the value from inputs
const passwordValue = password.value.trim();
const passwordRepeatValue = password_repeat.value.trim();
let return_value = false;
//These variables are set with one when the value of the input field is correct
let password_check = 0;
let password_repeat_check = 0;
if (passwordValue === '') {
//Show error and set error class
setError(password, 'Password field cannot be empty');
} else if (passwordValue.length <= 6) {
setError(password, 'Please enter a longer password');
} else {
//Add success class
setSuccess(password);
password_check = 1;
}
if (passwordRepeatValue === '') {
//Show error and set error class
setError(password_repeat, 'Password repeat field cannot be empty');
} else if (passwordValue !== passwordRepeatValue) {
setError(password_repeat, 'The passwords do not match');
} else if (passwordRepeatValue.length <= 6) {
setError(password_repeat, "Repeated password needs to be longer")
} else {
//Add success class
setSuccess(password_repeat);
password_repeat_check = 1;
}
if (name_check === 1 && email_check === 1 && password_check === 1 && password_repeat_check === 1) {
return_value = true;
} else {
return_value = false;
}
return return_value;
}
function setError(element, message) {
element.className = "form-control error";
const small = document.getElementById("message-" + element.id);
small.classList.remove('success');
//Add error message and icon
small.innerHTML = message + ' <i class="fas fa-exclamation-circle">';
//Add error class
small.classList.add("error");
}
const setSuccess = (element) => {
element.className = "form-control success";
const small = document.getElementById("message-" + element.id);
small.classList.remove('error');
//Add success icon
small.innerHTML = '<i class="fas fa-check-circle">';
//Add success class
small.classList.add("success");
}

How to pull the data from Google Sheets to Webapp after submitting a value from form?

I managed to work on a form that submits data to google sheets in the A column, After submitting the form in Column A, the formula does the calcuations in Columns B,C,D, I want to pull the data in Column B, Column C, and Column D results and display under the submit button.
What modification should be done for the following could be done?
My Google Sheets
My Form
Code.gs
function doGet(request) {
return HtmlService.createTemplateFromFile('Index')
.evaluate();
}
/* #Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
/* #Process Form */
function processForm(formObject) {
var url = "https://docs.google.com/spreadsheets/d/12G9g4aCbW41Js5wS33-7gTEO1r0SPh9lYauIJL53Jjk/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([formObject.number_data]);
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<?!= include('JavaScript'); ?>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-6">
<form id="myForm" onsubmit="handleFormSubmit(this)">
<p class="h4 mb-4 text-center">Values</p>
<div class="form-row">
<div class="form-group col-md-6">
<label for="number_data">Enter a Value</label>
<input type="text" class="form-control" id="number_data" name="number_data" placeholder="Enter Number">
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div id="output"></div>
</div>
</div>
</div>
</body>
</html>
JavaScript.html
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.processForm(formObject);
document.getElementById("myForm").reset();
}
</script>
In your processForm() function, Add a statement that will get the Col B, C, D of your newly added data and add a return statement which the callback function will use to write the data.
Try this:
Code.gs
/* #Process Form */
function processForm(formObject) {
var url = "Sheet url";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([formObject.number_data]);
var data = ws.getRange(ws.getLastRow(), 2, 1, 3).getValues();
return data;
}
JavaScript.html
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(writeData).processForm(formObject);
document.getElementById("myForm").reset();
}
function writeData(data){
document.getElementById("output1").innerHTML = data[0][0];
document.getElementById("output2").innerHTML = data[0][1];
document.getElementById("output3").innerHTML = data[0][2] ;
}
</script>
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<?!= include('JavaScript'); ?>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-6">
<form id="myForm" onsubmit="handleFormSubmit(this)">
<p class="h4 mb-4 text-center">Values</p>
<div class="form-row">
<div class="form-group col-md-6">
<label for="number_data">Enter a Value</label>
<input type="text" class="form-control" id="number_data" name="number_data" placeholder="Enter Number">
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div>
<div class="row">
<label>Data A : </label>
<div id="output1"></div>
</div>
<div class="row">
<label>Data B : </label>
<div id="output2"></div>
</div>
<div class="row">
<label>Data C : </label>
<div id="output3"></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Sheet:
Output:
References:
Class google.script.run
getValues

What are the methods to limit the number and time of alerts?

when I click on the "Todo Ekleyin" button, I get a warning. However, I would like this alert to appear only once per press, not multiple times, and can be pressed again after the alert disappears. How can I achieve this and?
Thank you in advance for your answer, good work. (If there is a method other than the method you suggested, I would be glad if you can write its name.)
// Tüm Elementleri Seçme
const form = document.querySelector("#todo-form");
const todoInput = document.querySelector("#todo");
const todoList = document.querySelector(".list-group");
const firstCardBody = document.querySelectorAll(".card-body")[0];
const secondCardBody = document.querySelectorAll(".card-body")[1];
const filter = document.querySelector("#filter");
const clearButton = document.querySelector("#clear-todos");
eventListeners();
function eventListeners() { // Tüm Event Listenerlar
form.addEventListener("submit", addTodo);
}
function addTodo(e) {
const newTodo = todoInput.value.trim();
if (newTodo === "") { // Alarm Verme
showAlert("danger","Lütfen Bir Todo Giriniz");
}
else {
addTodoToUI(newTodo);
}
addTodoToUI(newTodo);
e.preventDefault();
}
function showAlert(type,message){
const alert = document.createElement("div");
alert.className = `alert alert-${type}`;
alert.textContent = message;
firstCardBody.appendChild(alert);
//setTimeout
setTimeout(function(){
alert.remove();
}, 1000);
}
function addTodoToUI(newTodo) { // String Değerini List Item olarak Ekleyecek.
// List Item Oluşturma.
const listItem = document.createElement("li");
// Link Oluşturma
const link = document.createElement("a");
link.href = "#";
link.className = "delete-item";
link.innerHTML = "<i class = 'fa fa-remove'></i>";
listItem.className = "list-group-item d-flex justify-content-between";
// Text Node
listItem.appendChild(document.createTextNode(newTodo));
listItem.appendChild(link);
// Todo List'e List Item'ı Ekleme
todoList.appendChild(listItem);
// Ekleme Sonrası Input'tan yazı Silme
todoInput.value = "";
}
// Todo Ekleme Bilgi Mesajı
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />
<title>Todo List</title>
</head>
<body>
<div class="container" style="margin-top: 20px">
<div class="card row">
<div class="card-header">Todo List</div>
<div class="card-body">
<form id="todo-form" name="form">
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" type="text" name="todo" id="todo"
placeholder="Bir Todo Girin" />
</div>
</div>
<button type="submit" class="btn btn-danger">Todo Ekleyin</button>
</form>
<hr />
<!-- <div class="alert alert-danger" role="alert">
This is a danger alert—check it out!
</div> -->
</div>
<div class="card-body">
<hr />
<h5 class="card-title" id="tasks-title">Todolar</h5>
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" type="text" name="filter" id="filter"
placeholder="Bir Todo Arayın" />
</div>
</div>
<hr />
<ul class="list-group">
<!-- <li class="list-group-item d-flex justify-content-between">
Todo 1
<a href = "#" class ="delete-item">
<i class = "fa fa-remove"></i>
</a>
</li>-->
</ul>
<hr />
<a id="clear-todos" class="btn btn-dark" href="#">Tüm Taskları Temizleyin</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
</script>
<script src="berkay.js"></script>
</body>
</html>
You can put an integer in your alert function and every using array increase a one more.
For example, if you want after 5 times don't show alert.
var a = 0;
var b = true;
if (newTodo === "" || b) { // Alarm Verme
showAlert("danger","Please Give me a Todo!");
a++;
if(a == 5 ){
b = false;
}
}

Categories

Resources