JQuery TODO list, remove list removing everything - javascript

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.

Related

I want to change the color of card on click through Javascript have many cards and change single card color

Blockquote I want to change the color of my card when i press the mark as important button but when i add two or three cards and click on a mark as important of a single card it will change the color of all cards
Blockquote
i want that if i click on mark as important button then a single card color will changed it will not change the color of all cards
console.log("welcome to our website");
shownNotes();
impNotes();
let addbtn = document.getElementById("addbtn");
addbtn.addEventListener("click", handler)
function handler() {
let txtarea = document.getElementById("txtarea");
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
}
else {
notesObj = JSON.parse(notes);
}
notesObj.push(txtarea.value);
localStorage.setItem("notes", JSON.stringify(notesObj));
txtarea.value = "";
console.log(notesObj);
shownNotes();
}
function shownNotes() {
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
}
else
notesObj = JSON.parse(notes);
let html = "";
notesObj.forEach(function (element, index) {
html +=
`<div class="card mx-2 my-2 funny" style="width: 18rem;" >
<div class="card-body">
<h5 class="card-title">${index}</h5>
<p class="card-text">${element}</p>
<button id="${index} "onclick="delNotes(this.id)" class="btn btn-primary">Delete Note</button>
<button id="impbtn" onclick="impNotes(this.id)" class=" my-2 btn btn-primary">Mark Important</button>
</div>
</div>`
});
let notesElm = document.getElementById("notes");
if (notesObj.length != 0) {
notesElm.innerHTML = html;
}
else {
notesElm.innerHTML = "<b>Nothing to show</b>"
}
}
//function to delete notes
function delNotes(index) {
console.log("i m deleting", index)
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
}
else
notesObj = JSON.parse(notes);
notesObj.splice(index, 1);
localStorage.setItem("notes", JSON.stringify(notesObj));
shownNotes();
}
// function to imp notes
function impNotes() {
console.log("important function is firing ");
let impbtn = document.getElementsByClassName("funny");
Array.from(impbtn).forEach(function (element, index) {
element.style.backgroundColor = "yellow";
})
}
<!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>Magic Notes</title>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.4.1/dist/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.4.1/dist/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
</body>
</html>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Magic Notes</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<div class="container my-4 text-center">
<h1>WELCOME TO MAGIC NOTES </h1>
</div>
<div class="container-sm card text-center ">
<div class="card-body">
<h5 class="card-title">Add a Note </h5>
<div class="form-group">
<textarea class="form-control" id="txtarea" rows="3"></textarea>
</div>
<button class="btn btn-primary" id="addbtn">Click me to add Note </button>
</div>
</div>
<Hr>
<H1 class="text-center">Your Notes </H1>
<div class="row justify-content-center" id="notes"></div>
<!-- <hr> -->
<script src="app.js"></script>
</body>
</html>
The impNotes() function should take in a parameter that will help you identify which note color to change so impNote should be
function impNotes(id) {
console.log("important function is firing ");
let impbtn = document.getElementsByClassName("funny");
Array.from(impbtn).forEach(function (element, index) {
if(index === id)
element.style.backgroundColor = "yellow";
})
}
For you to pass argument to impNote you should change the code in showNotes()
function shownNotes() {
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
}
else
notesObj = JSON.parse(notes);
let html = "";
notesObj.forEach(function (element, index) {
html +=
`<div class="card mx-2 my-2 funny" style="width: 18rem;" >
<div class="card-body">
<h5 class="card-title">${index}</h5>
<p class="card-text">${element}</p>
<button id="${index} "onclick="delNotes(this.id)" class="btn btn-primary">Delete Note</button>
<button id="impbtn" onclick="impNotes(${index})" class=" my-2 btn btn-primary">Mark Important</button>
</div>
</div>`
});
let notesElm = document.getElementById("notes");
if (notesObj.length != 0) {
notesElm.innerHTML = html;
}
else {
notesElm.innerHTML = "<b>Nothing to show</b>"
}
}
You pass index to impNote
function shownNotes() {
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
}
else
notesObj = JSON.parse(notes);
let html = "";
notesObj.forEach(function (element, index) {
html +=
`<div class="card mx-2 my-2 funny" id="card-${index}" style="width: 18rem;" >
<div class="card-body">
<h5 class="card-title">${index}</h5>
<p class="card-text">${element}</p>
<button id="${index} "onclick="delNotes(this.id)" class="btn btn-primary">Delete Note</button>
<button id="impbtn" onclick="impNotes('card-${index}')" class=" my-2 btn btn-primary">Mark Important</button>
</div>
</div>`
});
let notesElm = document.getElementById("notes");
if (notesObj.length != 0) {
notesElm.innerHTML = html;
}
else {
notesElm.innerHTML = "<b>Nothing to show</b>"
}
}
pass the id for each card based on index as shown and pass the id to impNotes method
function impNotes(id) {
if(id) {
let impbtn = document.getElementById(id);
impbtn.style.backgroundColor = "yellow"
}
}

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");

implement JavaScript callback

I'm a beginner in Javascript I have an api which I need to execute asynchronously or I need a request to be executed only after the previous one is completed.
Researching I found that with Callback it is possible to do this, however I cannot implement it in my script.
Below is my HTML:
<!DOCTYPE html>
<html class="loading" lang="en" data-textdirection="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="description" content="Chameleon Admin is a modern Bootstrap 4 webapp & admin dashboard html template with a large number of components, elegant design, clean and organized code.">
<meta name="keywords" content="admin template, Chameleon admin template, dashboard template, gradient admin template, responsive admin template, webapp, eCommerce dashboard, analytic dashboard">
<meta name="author" content="Niklausec">
<title></title>
<link rel="apple-touch-icon" href="../../theme-assets/images/ico/apple-icon-120.png">
<link rel="shortcut icon" type="image/x-icon" href="theme-assets/images/logo/logo.png">
<link href="https://fonts.googleapis.com/css?family=Muli:300,300i,400,400i,600,600i,700,700i%7CComfortaa:300,400,700" rel="stylesheet">
<link href="https://maxcdn.icons8.com/fonts/line-awesome/1.1/css/line-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body class="vertical-layout vertical-menu 2-columns menu-expanded fixed-navbar" style="background: #0f1321;" data-open="click" data-menu="vertical-menu" data-color="bg-chartbg" data-col="2-columns">
<div class="container mt-4" style="margin-bottom: 100px;">
<div class="text-center mb-3">
<div class="text-center ">
<h1 class="text-light"><b></b> </h1>
<div class="text-center ">
</div>
<textarea class="form-control bg-dark text-light" style="resize: none;text-align: center;margin: auto;" rows="12" id="lista" placeholder="Informe sua lista"></textarea>
</fieldset>
<center>
<div class="mb-3">
<button type="button" class="btn btn-light btn-min-width mr-1 mb-1" id="testar" onclick="enviar()">INICIAR</button>
<button type="button" class="btn btn-light btn-min-width mr-1 mb-1" id="parar" disabled="true">PARAR</button>
VOLTAR
</div>
</center>
<center>
<div class="badge badge-success badge-pill" style="padding: 10px 10px;margin: 5px;">
<i class="la la-check"></i>
<span style="font-size: 15px;"> Aprovados</span>
<span style="font-size: 15px;" id="cLive">0</span>
</div>
<div class="badge badge-danger badge-pill" style="padding: 10px 10px;margin: 5px;">
<i class="la la-close"></i>
<span style="font-size: 15px;"> Reprovados</span>
<span style="font-size: 15px;" id="cDie">0</span>
</div>
<div class="badge badge-primary badge-pill" style="padding: 10px 10px;margin: 5px;">
<i class="la la-clock-o"></i>
<span style="font-size: 15px;"> Testados</span>
<span style="font-size: 15px;" id="total">0</span>
</div>
<div class="badge badge-info badge-pill" style="padding: 10px 10px;margin: 5px;">
<i class="la la-cloud-upload"></i>
<span style="font-size: 15px;"> Carregados</span>
<span style="font-size: 15px;" id="carregadas">0</span>
</div>
</center>
<center>
<div class="text-center text-light mt-3">
<h4 class="text-light" id="status_ccs">AGUARDANDO INICIO...</h4>
</div>
</center>
<div class="col-md-12 mt-3 p-0">
<div class="card bg-dark text-light">
<div style="position: absolute;top: 0;right: 0;">
<button id="mostra" class="btn btn-primary" style="padding: 2px 5px;"><i class="la la-external-link-square" style="font-size: 30px;"></i></button>
</div>
<div class="card-body">
<h6 style="font-weight: bold;" class="card-title text-light">Aprovados - <span id="cLive2" class="badge badge-success">0</span></h6>
<div id="bode"><span id=".aprovadas" class="aprovadas"></span></div>
</div>
</div>
</div>
<div class="col-md-12 mt-3 p-0">
<div class="card bg-dark text-light">
<div style="position: absolute;top: 0;right: 0;">
<button id="mostra2" class="btn btn-primary" style="padding: 2px 5px;"><i class="la la-external-link-square" style="font-size: 30px;"></i></button>
</div>
<div class="card-body">
<h6 style="font-weight: bold;" class="card-title text-light">Reprovados - <span id="cDie2" class="badge badge-danger">0</span></h6>
<div id="bode2"><span id=".reprovadas" class="reprovadas"></span></div>
</div>
</div>
</div>
</div>
<!-- BEGIN VENDOR JS-->
<script src="theme-assets/vendors/js/vendors.min.js" type="text/javascript"></script>
<!-- BEGIN VENDOR JS-->
<!-- BEGIN PAGE VENDOR JS-->
<script src="theme-assets/vendors/js/charts/chartist.min.js" type="text/javascript"></script>
<!-- END PAGE VENDOR JS-->
<!-- BEGIN CHAMELEON JS-->
<script src="theme-assets/js/core/app-menu-lite.js" type="text/javascript"></script>
<script src="theme-assets/js/core/app-lite.js" type="text/javascript"></script>
<!-- END CHAMELEON JS-->
<!-- BEGIN PAGE LEVEL JS-->
<script src="theme-assets/js/scripts/pages/dashboard-lite.js" type="text/javascript"></script>
<!-- END PAGE LEVEL JS-->
<script type="text/javascript">
$(document).ready(function(){
$("#bode").hide();
$("#esconde").show();
$('#mostra').click(function(){$("#bode").slideToggle();});
});
$(document).ready(function(){
$("#bode2").hide();
$("#esconde2").show();
$('#mostra2').click(function(){$("#bode2").slideToggle();});
});
function enviar() {
var linha = $("#lista").val();
var linhaenviar = linha.split("\n");
var total = linhaenviar.length;
if (total > 500) {
alert("Limite: 500 GERADEX POR TESTE!");
return;
}
var ap = 0;
var rp = 0;
$('#testar').attr('disabled', 'disabled');
$('#parar').attr('disabled', null);
var callBackFn = function(index) {
if (index >= linhaenviar.length) {
return;
}
var value = linhaenviar[index];
var ajaxCall = $.ajax({
url: 'afa.php?lista=' + value,
type: 'GET',
async: true,
success: function(resultado) {
if (resultado.match("APROVADO")) {
removelinha();
ap++;
aprovadas(resultado + "");
$('#status_ccs').html('APROVADO');
} else {
removelinha();
rp++;
reprovadas(resultado + "");
$('#status_ccs').html('');
}
$('#carregadas').html(total);
var fila = parseInt(ap) + parseInt(rp);
$('#cLive').html(ap);
$('#cDie').html(rp);
$('#total').html(fila);
$('#cLive2').html(ap);
$('#cDie2').html(rp);
if (fila == total) {
$('#testar').attr('disabled', null);
$('#parar').attr('disabled', 'disabled');
$('#lista').attr('disabled', null);
// audio.play();
document.getElementById("status_ccs").innerHTML = "FINALIZADO";
setTimeout(function() {
document.getElementById("status_ccs").innerHTML = "AGUARDANDO INICIO...";
}, 6000);
}
index++;
callBackFn(index);
}
});
$('#parar').click(function() {
ajaxCall.abort();
$('#testar').attr('disabled', null);
$('#parar').attr('disabled', 'disabled');
$('#lista').attr('disabled', null);
var st = 'PAUSADO';
$('#status_ccs').html(st);
});
}
callBackFn(0);
}
});
}
function aprovadas(str) {
$(".aprovadas").prepend(str + "<br>");
}
function reprovadas(str) {
$(".reprovadas").prepend(str + "<br>");
}
function removelinha() {
var lines = $("#lista").val().split('\n');
lines.splice(0, 1);
$("#lista").val(lines.join("\n"));
}
</script>
</body>
</html>
Expected Result:
I need only another call to be made in the API after the end of the later one and so on.
I changed your enviar function so that each ajaxCall is executed just after previous has finished.
Notice:
I created a variable "callBackFn". This is function that will be used as callback.
At the end of ajax success I executed this callBackFn.
function enviar() {
var linha = $("#lista").val();
var linhaenviar = linha.split("\n");
var total = linhaenviar.length;
if (total > 500) {
alert("Limite: 500 GERADEX POR TESTE!");
return;
}
var ap = 0;
var rp = 0;
$('#testar').attr('disabled', 'disabled');
$('#parar').attr('disabled', null);
var callBackFn = function(index) {
if (index >= linhaenviar.length) {
return;
}
var value = linhaenviar[index];
var ajaxCall = $.ajax({
url: 'afa.php?lista=' + value,
type: 'GET',
async: true,
success: function(resultado) {
if (resultado.match("APROVADO")) {
removelinha();
ap++;
aprovadas(resultado + "");
$('#status_ccs').html('APROVADO');
} else {
removelinha();
rp++;
reprovadas(resultado + "");
$('#status_ccs').html('');
}
$('#carregadas').html(total);
var fila = parseInt(ap) + parseInt(rp);
$('#cLive').html(ap);
$('#cDie').html(rp);
$('#total').html(fila);
$('#cLive2').html(ap);
$('#cDie2').html(rp);
if (fila == total) {
$('#testar').attr('disabled', null);
$('#parar').attr('disabled', 'disabled');
$('#lista').attr('disabled', null);
// audio.play();
document.getElementById("status_ccs").innerHTML = "FINALIZADO";
setTimeout(function() {
document.getElementById("status_ccs").innerHTML = "AGUARDANDO INICIO...";
}, 6000);
}
index++;
callBackFn(index);
}
});
$('#parar').click(function() {
ajaxCall.abort();
$('#testar').attr('disabled', null);
$('#parar').attr('disabled', 'disabled');
$('#lista').attr('disabled', null);
var st = 'PAUSADO';
$('#status_ccs').html(st);
});
}
callBackFn(0);
}
By the way, if you intend to process audio I would suggest using https://howlerjs.com/

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;
}
}

Blur event happens before datepicker fills the field

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?

Categories

Resources