implement JavaScript callback - javascript

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/

Related

how can I resolve sweetalert background distortion?

enter image description here
Upper image is the Sign-in page.
I added sweetalert, and it goes wrong like below.
(the alert set in the middel, and my sign-in form goes up! It should be located in the middle!)
(I added the alert appear when the ID or password value is null or empty.)
login equals sign-in
what's wrong with my code?
Here is my full code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9"></script>
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.101.0">
<title>Floating labels example · Bootstrap v4.6</title>
<!-- Bootstrap core CSS -->
<!-- <link href="/css/bootstrap.min.css" rel="stylesheet">-->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/product/">
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="/css/floating-labels.css" rel="stylesheet">
</head>
<body>
<div class="form-signin" style="max-width: 520px">
<div class="text-center mb-4">
<!-- TODO 로그인페이지 로고 추가할 자리 -->
<!-- <img class="mb-4" src="/brand/bootstrap-solid.svg" alt="" width="72" height="72">-->
<h1 class="h3 mb-3 font-weight-normal">로그인 </h1>
</div>
<div class="form-label-group">
<input id="user_id" class="form-control" placeholder="id" required autofocus>
<label for="inputId">ID를 입력하세요</label>
</div>
<div class="form-label-group">
<input type="password" id="password" class="form-control" placeholder="Password" required>
<label for="inputPassword">Password를 입력하세요</label>
</div>
<div>
<button class="btn btn-outline-primary form-control" id="loginBtn" onclick="login()">로그인</button>
</div>
<hr class="mb-4">
<div class="btn-group row" style="width:100%; --bs-gutter-x: 0">
<button class="btn btn-sm btn btn-outline-secondary btn-block col-4" type="button" style="font-size:16px;">아이디
찾기
</button>
<button class="btn btn-sm btn btn-outline-secondary btn-block col-4" type="button" style="font-size:16px;">비밀번호
찾기
</button>
<button class="btn btn-sm btn btn-outline-secondary btn-block col-4" type="button" style="font-size:16px;"
onclick="joinBtn()">회원가입
</button>
</div>
<p class="mt-5 mb-3 text-muted text-center">© 2017-2022</p>
</div>
</body>
</html>
<script>
var input = document.getElementById("password");
input.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
event.preventDefault();
document.getElementById("loginBtn").click();
}
});
var passwordForm = document.querySelector("#password");
function login() {
let userIdValue = document.querySelector("#user_id").value;
let passwordValue = document.querySelector("#password").value;
if (userIdValue == null || userIdValue == "") {
document.querySelector("#user_id").focus();
Swal.fire(
'ID가 비었습니다!',
'로그인 할 계정의 ID를 입력해주세요!',
'question'
)
return;
}
if (passwordValue == null || passwordValue == "") {
document.querySelector("#password").focus();
Swal.fire(
'비밀번호가 비었습니다!',
'로그인 할 계정의 비밀번호를 입력해주세요!',
'question'
)
return;
}
let info = {
userId: userIdValue,
password: passwordValue
}
$.ajax({
url: "/login/check/api",
method: "POST",
contentType: "application/Json",
data: JSON.stringify(info),
success: function (a) {
location.href = "/"
},
error: function (a, b) {
let errorA = a
Swal.fire({
icon: 'error',
title: '로그인 실패',
text: errorA.responseText,
})
//alert(a.responseText);
}
})
}
function joinBtn() {
location.href = "/join/form"
}
</script>
let me know how can I solve this problem
Before the alert comes out, I think the HTML should be on the screen first to solve the problem, but I don't know what to do.

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.

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

Jquery-ui dialog error

Hi huys as you can see here I am having a dialog not found issue . I know this is part of jquery ui which i think i have loaded correctly but it still seems to not be working .
Error:
Uncaught TypeError: $(...).dialog is not a function(anonymous function)
# fablinker.php:524jQuery.event.handle
# jq.js:1936elemData.handle.eventHandle
# jq.js:1599
And here is my code guys , and help would be great been stuck on this with days now. Thanks
<?php
// //identify which user is logged in so the right profile info can be pulled up from dbase
// session_start();
// $UserN = $_SESSION['UserN'];
// if(isset($_SESSION['UserN']))
// {
// //$CurrentUser = $_SESSION['UserID'];
// $UserN = $_SESSION['UserN'];
// }
// else
// {
// header("location:index.php");
// }
if (isset($_REQUEST["casestudyid"]))
{
$casestudyid = $_REQUEST["casestudyid"];
}
else
{
$casestudyid = "";
}
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Fab Linker</title>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="IE.css" />
<![endif]-->
<!--[if IE 8.0000]>
<link rel="stylesheet" type="text/css" href="IE8.css" />
<![endif]-->
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/webflow.css">
<link rel="stylesheet" type="text/css" href="css/fab/main.css" />
<link rel="stylesheet" type="text/css" href="css/fab/style.css" />
<link rel="stylesheet" href="css/fab/jquery.tooltip.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="css/dolearnfinance-aab51d.webflow.css">
<link rel="stylesheet" type="text/css" href="css/fab/myFab.css" />
<link rel="stylesheet" href="js/fablinker/jquery/jquery-ui.min.css">
<script src="js/fablinker/jquery/external/jquery/jquery.js"></script>
<script src="js/fablinker/jquery/jquery-ui.min.js"></script>
<script src="js/fablinker/popup.js" type="text/javascript"></script>
<script src="js/fablinker/jq.js" type="text/javascript"></script>
<script src="js/fablinker/fab.js" type="text/javascript"></script>
<script type="text/javascript" src="js/fablinker/jquery.tooltip.js"></script>
<script type="text/javascript" src="js/fablinker/jquery.corner.js"></script>
<link href='https://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="navscroll" data-collapse="medium" data-animation="default" data-duration="400" class="w-nav navbarone notfixed">
<div class="w-container"><h1 class="logo-text">do<span class="pinktext">Learn</span>Finance</h1>
<nav role="navigation" class="w-nav-menu w-clearfix nav-menu">HomeAboutContactsign in
</nav>
<div class="w-nav-button">
<div class="w-icon-nav-menu"></div>
</div>
</div>
</div>
<div class="w-section head-section">
<div class="w-container">
<h1 class="course-headings">Fablinker</h1>
<div class="breadcrums-div">
<a href="index.php" class="w-inline-block breadcrum">
<div class="breadcrum-text">HOME</div>
</a>
<div class="breadcrum next">></div>
<a href="index.php" class="w-inline-block breadcrum">
<div class="breadcrum-text">course</div>
</a>
<div class="breadcrum next">></div>
<a href="learn_home.php" class="w-inline-block breadcrum">
<div class="breadcrum-text">Learn</div>
</a>
<div class="breadcrum next">></div>
<a href="fablinker.php" class="w-inline-block breadcrum">
<div class="breadcrum-text">Fablinker</div>
</a>
</div>
</div>
</div>
<div class="w-section main-section ">
<!--######################################################################################################-->
<div id="parent">
<div id="topDiv">
<!-- <div id="mainmenu">
<div id="btnNew" class="menuButton">New</div>
<div id="btnLoad" class="menuButton">Load</div>
<div id="btnSave" class="menuButton">Save</div>
<div id="btnDelete" class="menuButton">Delete</div>
<div id="btnTutor" class="menuButton">Tutor On</div>
<div id="btnHelp" class="menuButton">Glossary</div>
</div> -->
New LoadSaveDeleteTutorGlossary
</div>
<!-- Begin Wrapper -->
<div id="wrapper">
<!-- Begin Left Column -->
<div id="leftcolumn">
<div id="divInputs" class="exerciseColumn">
<div id="divInputs_SellingAndBuyingGoods"></div>
<div id="divInputs_OverheadExpenses"></div>
<div id="divInputs_Funding"></div>
<div id="divInputs_FixedAssets"></div>
</div>
</div>
<!-- End Left Column -->
<!-- Begin PnL Col -->
<div id="content">
<div id="hdg">
<h3 class ="fablinkerheading" >Profit/Loss Account</h3>
<div class="htmltooltip" id="htt23" style="width: 170px;">
<p class="tipText" >Is a financial statement which shows the net profit or loss of a business for a given accounting period.It is essentially a statement of the "income generating" performance of the business.</p>
</div>
<i class ="i-space" style="color:black;">(Projected)</i>
</div>
<div id="divOutputs_PNL" class="exerciseColumn">
<div id="divOutputs_Sales_PNL"></div>
<div id="divOutputs_CashFlow_PNL"></div>
</div>
</div>
<div id="content">
<div id="hdg">
<h3 style="color: black" >Balance Sheet</h3>
<div class="htmltooltip" id="htt23" style="width: 170px;">
<p class="tipText" >
Is a financial statement which shows the net profit or loss of a business for a given accounting period.
It is essentially a statement of the "income generating" performance of the business.</p>
</div>
<i style="color:black;">(Projected)</i>
</div>
<br/>
<div id="divOutputs_BS" class="exerciseColumn">
<div id="divOutputs_FixedAssets_BS"></div>
<div id="divOutputs_CurrentAssets_BS"></div>
<div id="divOutputs_CurrentLiabilities_BS"></div>
<div id="divOutputs_Assets_BS"></div>
<div id="divOutputs_RepresentedBy_BS"></div>
</div>
</div>
<!-- End Content Column -->
<!-- Begin Right Column ############################################################################################## -->
<!-- Begin PnL Col -->
<!-- End Content Column -->
<div id="rightcolumn">
<div id="hdg">
<h3 style="color: black;" >Operating Ratios</h3>
<div class="htmltooltip" id="htt43" style="width: 170px;" >
<p class="tipText">
The balance sheet is a statement of the financial position of a business at a given date.
It is normally based on historical costs and discloses the book value of the assets, liabilities, share capital and reserves.</p>
</div>
<i style="color: black;">(Projected)</i>
<div id="menu" style="border-style: 2px solid red; padding: 5px; margin-left: 19px; ;margin-top: -43px; background:#195e93; float:right; width:95px; height: 83px;" class="invisible">
<div style="padding: 3px; float: right;">
Home<br/>
About Us<br/>
Support<br/>
Log Out
</div>
</div>
</div>
<div id="divOutputs_RAT" class="exerciseColumn">
<div id="divOutputs_ProfitLossRatios_RAT"></div>
<div id="divOutputs_LiquidityRatios_RAT"></div>
<div id="divOutputs_WorkingCapitalRatios_RAT"></div>
<div id="divOutputs_GearingRatios_RAT"></div>
<div id="divOutputs_VolumeRatios_RAT"></div>
</div>
</div>
<!-- End Right Column -->
<br>
</div> <!-- end -->
</div> <!-- end of wrapper -->
</div>
<div id="dlgNew" class="fldialog">
<h3>New Case Study</h3>
Create a new case study.
<br/>
Name:<input type="text" id="newName"/><br/>
Description:<input type="text" id="newDescription"/><br/>
</div>
<div id="dlgLoad" class="fldialog">
Load a case study:
<select id="selCaseStudies">
</select>
</div>
<div id="dlgDelete" class="fldialog">
Delete a case study:
<select id="selCaseStudiesToDelete">
</select>
</div>
<div id="dlgSave" class="fldialog">
Save:<br/>
Name:<input type="text" id="saveName"/><br/>
Description:<input type="text" id="saveDescription"/><br/>
</div>
<!--End Parent Div -->
<script type="text/javascript" src="js/fablinker/BusinessLogic-min.js"></script>
<script type="text/javascript" src="js/fablinker/fablinkerObjects-min.js"></script>
<script type="text/javascript" src="js/fablinker/jquery.helpify.js"></script>
<?php echo("<script type='text/javascript'>var casestudyid = '$casestudyid';</script>");?>
<script type="text/javascript">
var currentCSName;
var currentCSDescription;
var currentCSID;
var bNotSaved;
$(document).ready(function(){
$('#wrapper').corner();
bSaved = true;
$('#dlgNew').hide();
$('#btnTutor').html('Tutor Off');
$('#btnTutor').addClass('menuButton_Selected');
initMapObjects();
// reset the figures
if (!casestudyid)
{
newCaseStudy();
}
else
{
loadCaseStudy(casestudyid);
}
//configureDependenciesForOutputs();
configureDependencyTree();
recalcAll();
$('#btnNew').click(function(evt){
if (confirm("New Casestudy"))
{
currentCSName = "";
$('#currentCSName').val("");
currentCSDescription = "";
$('#currentCSDescription').val("");
currentCSID = -1;
bSaved = true;
newCaseStudy();
recalcAll();
}
// don't call the home button handler
//evt.stopPropagation();
});
$('#btnRecalc').click(function(evt){
recalcAll();
//alert("recalc(Netassets_BS)");
//om["Netassets_BS"].evaluate();
});
$('#topDiv').click(function(evt){
if (evt.originalTarget == evt.currentTarget)
{
window.location.href="userhome.php";
}
});
$('#btnLoad').click(function(evt) {
// empty the list
$('#selCaseStudies').find('option').remove();
// populate the list of case studies
$.getJSON("dbs/gcsl.php", function(data){
$.each(data, function(key, value){
//alert(key + ":" + value);
$('#selCaseStudies').append("<option value='" + key + "'>" + value[1] + "-" + value[2] + "</option>");
});
});
// show the dialog
$('#dlgLoad').dialog({
buttons: {
"Ok" : function() {
$(this).dialog("close");
var csd = {};
csid = $('#selCaseStudies').val();
//csid = prompt("casestudyid", "1");
loadCaseStudy(csid);
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
// don't call the home button handler
evt.stopPropagation();
});
$('#btnDelete').click(function(evt) {
// empty the list
$('#selCaseStudiesToDelete').find('option').remove();
// populate the list of case studies
$.getJSON("dbs/gcsl.php", function(data){
$.each(data, function(key, value){
//alert(key + ":" + value);
$('#selCaseStudiesToDelete').append("<option value='" + key + "'>" + value[1] + "-" + value[2] + "</option>");
});
});
// show the dialog
$('#dlgDelete').dialog({
buttons: {
"Ok" : function() {
var csd = {};
csid = $('#selCaseStudiesToDelete').val();
if (confirm("Delete Casestudy")) {
deleteCaseStudy(csid);
//alert ("deleting");
$(this).dialog("close");
//$.getJSON("dbs/dcs.php?csid=" + csid, function(data){
//});
currentCSName = "";
$('#currentCSName').val("");
currentCSDescription = "";
$('#currentCSDescription').val("");
currentCSID = -1;
bSaved = true;
newCaseStudy();
recalcAll();
}
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
// don't call the home button handler
evt.stopPropagation();
});
$('#btnTutor').click(function(evt) {
if ($('#btnTutor').hasClass('menuButton_Selected'))
{
$('#btnTutor').html('Tutor On');
$('#btnTutor').removeClass('menuButton_Selected');
$('.imginfo').hide();
}
else
{
$('#btnTutor').html('Tutor Off');
$('#btnTutor').addClass('menuButton_Selected');
$('.imginfo').show();
}
// don't call the home button handler
evt.stopPropagation();
});
$('#btnTest').click(function() {
$("#txtSellingPrice").keyup(function(e)
{
alert("hello");
});
});
$('#btnEvaluate').click(function() {
for (var o in om)
{
//alert(om[o].inputDependencies);
om[o].evaluate();
}
});
$('#btnExpand').click(function () {
if ($('#exerciseHeader').height() == 100) {
$('#exerciseHeader').animate({
height:"25px"
}, 500);
}
else
{
$('#exerciseHeader').animate({
height:"100px"
}, 500);
}
});
$("#dlgHelp").helpify();
$('#btnHelp').click(function(evt){
showHelpForTopic("dlgHelp", 1);
});
$('#btnTest').click(function(evt) {
showHelpForFlid("dlgHelp", "CostOfSales_PNL");
});
$('.helplink').click(function(evt) {
alert('hello');
});
$('#btnSave').click(function(evt) {
var csd = {};
csid = currentCSID;
$('#saveName').val(currentCSName);
$('#saveDescription').val(currentCSDescription);
// show the save dialog
$('#dlgSave').dialog({
buttons: {
"Ok" : function() {
$(this).dialog("close");
saveName = $('#saveName').val();
saveDescription = $('#saveDescription').val();
if (saveName != currentCSName)
{
// save as
csid = -1;
$('#currentCSName').val(saveName);
$('#currentCSDescription').val(saveDescription);
}
currentCSName = saveName;
currentCSDescription = saveDescription;
$.each(im, function(index, value) {
console.log(index + " " + value.value);
csd[index] = value.value;
});
//for (item in im)
//{
// csd[item] = im[item].value;
//}
var data = "csid=" + csid
+ "&csn=" + currentCSName
+ "&csdesc=" + currentCSDescription
+ "&csd=" + JSON.stringify(csd);
jQuery.ajax({
url:"dbs/scs.php",
data:data,
type:"post",
success:function(resp){
currentCSID = parseInt(resp);
//alert("saved:" + currentCSID);
alert("saved");
},
error:function(e){
alert("failed to save");
}
});
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
// don't call the home button handler
evt.stopPropagation();
});
});
</script>
</body>
<footer>
<div class="w-container">
<div class="w-row">
<div class="w-col w-col-3">
<h1 class="logo-text">do<span class="pinktext">Learn</span>Finance</h1>
</div>
<div class="w-col w-col-6">
<div class="centered">
<a href="index.php" class="w-inline-block footer-link">
<div class="footer-link">Home</div>
</a>
<a href="about.php" class="w-inline-block footer-link">
<div class="footer-link">About</div>
</a>
<a href="contact.php" class="w-inline-block footer-link">
<div class="footer-link">Contact</div>
</a>
<a href="#" class="w-inline-block footer-link">
<div class="modal-link footer-link">Sign In</div>
</a>
</div>
</div>
<div class="w-col w-col-3">
<div>
</div>
</div>
</div>
</footer>
</html>

Getting "is not defined" loading a function from external javascript

I have two files: index.php and local.js.
This is index.php:
<!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">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">
<!-- FontAwesome: font-set designed for Bootstrap -->
<link href="css/font-awesome.css" rel="stylesheet">
<title>Befair-Timetracker</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/time.css" rel="stylesheet">
<!-- Template HTML to build up a new row on the table -->
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../docs-assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<?php
//include("dbconn.php");
?>
<div class="navbar navbar-inverse navbar-fixed-top navbar-time" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle navbarbtn" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Timetracker</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">Tracking</li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="Email" class="form-control input-sm">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control input-sm">
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>
</div><!--/.navbar-collapse -->
</div>
</div>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron jumbotime">
<div class="container">
<h1 class="time">Timetracker management</h1>
<p class="timepar">Nella tabella sottostante verranno inserite la varie attività, classificabili in base al proprio CH e agli utenti che le svolgono.</p>
<!--<p><a class="btn btn-primary btn-lg" role="button">Learn more »</a></p>-->
</div>
</div>
<div class="container">
<h3 class="time">Risultati attesi</h3>
<hr>
<div class="selection"> <!-- inserire well nella classe per ottenere riquadro blu -->
<span class="titolosel">Centro di costo</span>
<select class="form-control selecttime">
</select>
</div>
<hr>
<!-- Table containing the info about CH, users and RA -->
<table id ="timetable" class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Users</th>
<th>Activities</th>
<th>Timer</th>
</tr>
</thead>
<tbody class="ra hide">
</tbody>
</table>
<footer>
© BeFair 2013 - Website developed by Riccardo Pancotti
<div class="pull-right">
<!--<img src="images/beFair.jpg" alt="beFair-logo" class="img-rounded imglogo">-->
</div>
</footer>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.js"></script>
<script type="text/javascript" src="js/jquery.tmpl.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/local.js"></script>
<script type="text/javascript" charset="utf-8">
//**ANIMATED DIV/TABLE/TIMER**
function showact(ID){
$(".tr-act"+ID).animate({"height": "toggle"}, { duration: 300 });
//$(".hide").animate({"display":"toggle"}, { duration: 300 });
}
</script>
<script type="text/javascript" charset="utf-8">
//**LOADING JSON**
$(document).ready(function()
{
starttimer(2);
$.getJSON('js/test2.json', function(json) {
$.each(json.ch,function(key,val)
{
var chname=("<option value="+val.name+">"+val.name+"</option>");
$(".selecttime").append(chname);
});
});
});
</script>
<script type="text/javascript" charset="utf-8">
//$(document).ready(startimer(4));
//**CENTRO DI COSTO SELECTION**
$('.selecttime').change(function()
{
var pippo = "";
console.clear();
//setValue();
var pippo = $('.selecttime').val();
var chtable=("<tbody class=\"ra\"><tr>");
$.ajaxSetup( { "async": false } ); //Chiamata asincrona al server per il JSON
$.getJSON('js/test3.json', pippo,function(json) {
for (var i = 0, len = json.ch.length; i < len; i++) {
var namera = json.ch[i].name;
console.log(namera);
if (pippo === namera)
{
console.log("RA " +json.ch[i].ra_list.length);
for (var k = 0, lungh = json.ch[i].ra_list.length; k < lungh; k++)
{
//CICLO PER AGGIUNGERE NUOVE RA
var print = json.ch[i].ra_list[k];
chtable +=("<td>"+print.id+"</td>");
chtable +=("<td>"+print.name+"</td>");
chtable +=("<td>"+print.users+"</td>");
//***VECCHIA RIGA, MOSTRA TIMER***
//chtable +="<td><i class=\"fa fa-plus-square\"></i></td>";
//********************************
chtable +="<td class=\"timertd\"><i class=\"fa fa-plus-square\">+</i></td>";
chtable +="<td></td>";
console.log("Attività " + print.activities.length);
tract = "";
list_act = "";
count = 0;
for (var j = 0, lungh_in = json.ch[i].ra_list[k].activities.length; j < lungh_in; j++)
{
//CICLO PER AGGIUNGERE NUOVE ATTIVITA'
list_act += ("<tr style=\"display:none\" class=\"tr-act"+k+"\">");
list_act += "<td></td><td></td><td></td>";
list_act += "<td>";
list_act += print.activities[j].name;
list_act += "</td>";
list_act += "<td>" + "setValue()" + "</td>";
list_act += ("</tr>");
count++;
}
chtable += list_act;
chtable += "</tr>";
$(".ra").replaceWith(chtable);
}
}
}
});
});
</script>
</body>
</html>
And this is local.js:
var starttimer = function(idt)
{
alert(idt);
};
I'm trying to call this function here (it's part of the index.html):
<script type="text/javascript" charset="utf-8">
//**LOADING JSON**
$(document).ready(function()
{
starttimer(2);
$.getJSON('js/test2.json', function(json) {
$.each(json.ch,function(key,val)
{
var chname=("<option value="+val.name+">"+val.name+"</option>");
$(".selecttime").append(chname);
});
});
});
</script>
but it keeps telling me "function is not defined".
What's the problem?
Probably it's something about the scope but i don't know what.
Solved, i was refering to the wrong file.

Categories

Resources