Including created javascript files in html - javascript

Somehow I can't create external javascript files. If I import them from other examples, they work fine but if it is files I create and import them, they don't work. They are working fine if I inclued them into the html but if I reference them they don't work. I don't know what I am doing wrong.
Here's my html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Documento sem título</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.ui.draggable.js" type="text/javascript"></script>
<!-- Core files -->
<script src="jquery.alerts.js" type="text/javascript"></script>
<body>
<script type="text/javascript" src="horario.js"></script>
<div id="entrada">
<input id="time" class="inputs" type="text" maxlength="2"></input>
<input id="time2" class="inputs" type="text" maxlength="2"></input>
<button class="inputs" id="confirm_button" class="inputs1" onKeyPress="localStore()" onClick="localStore()">entrada</button>
</div>
<div id="result"></div>
<div id="millsentr"></div>
<div id="millssai"></div>
<div id="mills"></div>
<div id="totHoras"></div>
</body>
</html>
And here's the javascript file:
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
$(".inputs1").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
$(document).ready( function() {
$("#confirm_button").click( function() {
jConfirm('Can you confirm this? ', 'Confirmation Dialog', function(r) {
var entradasaida = 0;
entradasaida = localStorage.getItem("entradasaida");
if(r == true){
if(entradasaida == 0){
var time = $('#time').val();
var time2 = $('#time2').val();
var datetime = new Date();
var year = datetime.getFullYear();
var month = datetime.getMonth()+1;
if(month < 10){
month = "0"+month
}
var day = datetime.getDay()+1;
if(day < 10){
day = "0"+day
}
var date = new Date(year+"-"+month+"-"+day+" "+time+":"+time2);
var mills = date.getTime();
localStorage.setItem("horas", time);
localStorage.setItem("mins", time2);
localStorage.setItem("entradasaida",1);
localStorage.setItem("millsEnt",mills);
$('#confirm_button').text("Saida");
$('#time, #time2').val("");
$('#millsentr').text(mills);
} else{
var horasEnt = localStorage.getItem("horas");
var minsEnt = localStorage.getItem("mins");
var entrada = localStorage.getItem("millsEnt");
localStorage.setItem("entradasaida",0);
$('#confirm_button').text("Entrada");
var time = $('#time').val();
var time2 = $('#time2').val();
var datetime = new Date();
var year = datetime.getFullYear();
var month = datetime.getMonth()+1;
if(month < 10){
month = "0"+month
}
var day = datetime.getDay()+1;
if(day < 10){
day = "0"+day
}
var date1 = new Date(year+"-"+month+"-"+day+" "+time+":"+time2);
var millssai = date1.getTime();
$('#millssai').text(millssai);
var totMills = (millssai - entrada)
var horas = time - horasEnt;
var mins = time2 - minsEnt;
if(mins < 0){
mins = mins*(-1);
horas = horas-1;
}
var totHoras = horas+":"+mins
$('#totHoras').text(totHoras);
$('#mills').text(totMills);
$('#time, #time2').val("");
}
} else{r == false}
});
});
});
In this, the horario.js is the file I created and is not working, the other script files I used from examples are working ok.

Related

Javascript Clock - Clock is empty despite full program

I have poured over this code and I feel pretty positive about it. That being said, something is obviously missing, as the program itself comes up with an empty clock when run in the browser. I know that the brackets and parentheses all have a matching set, and I am fairly confident in my functions. The chrome developer tools were unhelpful. Anyone with a good eye for Javascript able to see what is missing here?
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var displayCurrentTime = function() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec today.getSeconds();
var ap = "AM";
if (hour > 12) {
h = h - 12;
ap = "PM";
} else {
switch (hour) {
case 12:
ap = "PM";
break;
case 0:
ap = "AM";
break;
}
}
$("hours").firstChild.nodeValue = padSingleDigit(hours);
$("minutes").firstChild.nodeValue = padSingleDigit(min);
$("seconds").firstChild.nodeValue = padSingleDigit(sec);
$("ap").firstChild.nodeValue = padSingleDigit(ap);
};
var padSingleDigit = function(num) {
if (num < 10) {
return "0" + num;
} else {
return num;
}
};
window.onload = function() {
displayCurrentTime();
setInterval(displayCurrentTime, 1000);
};
<html>
<head>
<meta charset="UTF-8">
<title>Clock</title>
<link rel="stylesheet" href="clock.css">
<script src="clock.js"></script>
</head>
<body>
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="hours"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
</body>
</html>
You simply have a lot of (3) typos ...
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var displayCurrentTime = function() {
var today = new Date();
var hour = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
var ap = "AM";
if (hour > 12) {
hour = hour - 12;
ap = "PM";
} else {
switch (hour) {
case 12:
ap = "PM";
break;
case 0:
ap = "AM";
break;
}
}
$("hours").firstChild.nodeValue = padSingleDigit(hour);
$("minutes").firstChild.nodeValue = padSingleDigit(min);
$("seconds").firstChild.nodeValue = padSingleDigit(sec);
$("ampm").firstChild.nodeValue = padSingleDigit(ap);
};
var padSingleDigit = function(num) {
if (num < 10) {
return "0" + num;
} else {
return num;
}
};
window.onload = function() {
displayCurrentTime();
setInterval(displayCurrentTime, 1000);
};
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="hours"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
*there are other (non-functional) problems in this code, but since it is not the Q, I'd not change them to keep this answer on point.

calculating time wit dynamic input

I have this script
<input type="hidden" id="from_t" value="<?= date('H:i',strtotime($row['from_t'])) ?>">
<input style="width: 50px" type="number" id="h" min="0" class="trvael">
$(document).on('change','.trvael',function () {
var form_t = $('#from_t').val(); // 10:00
var total_time = 5;
var travel_h = $('#h').val(); //user dynamic input
var sum = form_t - (parseFloat(total_time) + parseFloat(travel_h)) ;
})
How can I claculate all the values and get new time.
For example :
10:00 - 5 - 2.5 = 02:30
Thank you!
You can try something like this.
var from_t = '10:00'
var value1 = '5';
var value2 = '2.5';
var date = new Date();
var splits = from_t.split(':');
date.setHours(splits[0]);
date.setMinutes(splits[1]);
date.setMinutes(date.getMinutes() - ((+value1) + (+value2)) * 60);
console.log(date.getHours() + ':' + date.getMinutes());
I'm pretty sure you want something like my DateTime constructor to handle the job. I've already created this, so:
//<![CDATA[
/* js/external.js */
function DateTime(dateElement, timeElement, dateInstance){
var t = this;
this.dateElement = dateElement; this.timeElement = timeElement;
this.date = dateInstance instanceof Date ? dateInstance : new Date;
this.dateValue = function(dateInstance){
if(dateInstance instanceof Date)this.date = dateInstance;
var dt = this.date;
return dt.getFullYear()+'-'+(dt.getMonth()+1).toString().replace(/^(\d)$/, '0$1')+'-'+dt.getDate().toString().replace(/^(\d)$/, '0$1');
}
this.showDate = function(dateInstance){
this.dateElement.value = this.dateValue(dateInstance);
return this;
}
this.timeValue = function(dateInstance){
if(dateInstance instanceof Date)this.date = dateInstance;
var dt = this.date;
return dt.getHours().toString().replace(/^(\d)$/, '0$1')+':'+dt.getMinutes().toString().replace(/^(\d)$/, '0$1');
}
this.showTime = function(dateInstance){
this.timeElement.value = this.timeValue(dateInstance);
return this;
}
this.showDate().showTime();
this.dateChange = function(changeFunc, noTimeFunc){
this.dateElement.oninput = function(){
var v = this.value, s = t.timeElement.value;
if(v === '')v = this.value = t.dateValue(noTimeFunc(t));
if(s === '')s = t.timeValue(this.date);
t.date = new Date(v+' '+s); changeFunc(t.date, t);
}
return this;
}
this.timeChange = function(changeFunc, noTimeFunc){
this.timeElement.oninput = function(){
var v = this.value, s = t.dateElement.value;
if(v === '')v = this.value = t.timeValue(noTimeFunc(t));
if(s === '')s = t.dateValue(this.date);
t.date = new Date(s+' '+v); changeFunc(t.date, t);
}
return this;
}
}
$(function(){ // jQuery load
var dt = new DateTime($('#date')[0], $('#time')[0]);
function consoleIt(dateInstance){
console.log('display of dt.date --> '+dateInstance.toString());
console.log('dt.date for server --> '+dateInstance.getTime());
}
consoleIt(dt.date);
dt.dateChange(function(r){
consoleIt(r);
}).timeChange(function(a){
consoleIt(a);
});
}); // end load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='content'>
<input id='date' type='date' value=''/><input id='time' type='time' value='' />
</div>
</body>
</html>
Of course, you could use jQuery DatePicker, but that doesn't do time.
If you add another Date instance argument to DateTime you can set the default.

I don't get output after insert an input date

I have a function that gets the birthdate and don't print the output which is the sign according to the birthdate
I want the output to be under the send button (where id=output) currently works only with alert
another possibility is that the output will be in an input text.
Do you have any solution instead of alert as an output?
function yourSign() {
var signDate = $("input[name='birthDate']").val();
tempSignDate = signDate.split("-").join("/");
newSignDate = tempSignDate.substring(5, 10);
var AriesDateFrom = "21/03";
var AriesDateTo = "20/04";
var TaurusDateFrom = "21/04";
var TaurusDateTo = "20/05";
var Ad1 = AriesDateFrom.split("/");
var Ad2 = AriesDateTo.split("/");
var Td1 = TaurusDateFrom.split("/");
var Td2 = TaurusDateTo.split("/");
var s = newSignDate.split("/");
if (newSignDate == "") {
alert("enter birthday");
}else if (s >= Ad1 && s < Ad2) {
document.getElementById("output").innerHTML = "Aries";
}else if (s >= Td1 && s < Td2) {
document.getElementById("output").innerHTML = "Taurus";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
<meta charset="utf-8" />
<!--<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous">
</script>-->
</head>
<body>
<div>
<form>
<label for=birthDate>birthdate</label><br /><input type="date" name="birthDate" id="birthDate" /><br />
<button onclick="yourSign()">send</button><br />
<label> your sign is </label><br />
<p id="output"></p>
<!--<input type="text" name="output" id="output" />-->
</form>
</div>
</body>
</html>
split() creates an array. You can not directly compare arrays as a whole.
Your arrays has two elements: day number and month number.
Day is always index 0 in your snippet.
Month is always index 1.
Try to compare your arrays in steps:
if ( s[1] >= Ad1[1] && s[0] >= Ad[0] && s[1] <= Ad2[1] && s[0] <= Ad2[0]) { [...] };

JQuery slider for showing date interval

I am trying to show appropriate date according to slider position.This slider runs automatically till the end and shows what is the current date. So, problem is when i slide it back is not showing appropriate date. Any help please?
Here is the full code!
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Slider - Default functionality</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
var i = 1, k = 1;
var isPaused = false;
var eventNum=0;
var inter;
var ar = [];
function startSlider(interval, seconds)
{
var seconds = seconds*1000;
var tmp = interval;
var st = Math.ceil(1000/interval);
inter = setInterval(function()
{
$( "#slider" ).slider(
{
range: "min",
max:1000,
slide: function()
{
if (isPaused)
{
i=$(this).slider("value")+1;
}
else
{
alert("Pause to slide!");
}
}
});
if(!isPaused)
{
if(k%st == 0)
{
setDate(++eventNum);
ar[eventNum] = $("#slider").slider("value");
k = 1;
if (eventNum==interval)
{
clearInterval(inter);
while(i!=1000){
$("#slider").slider("value",i++);
}
}
}
k++;
$("#slider").slider("value",i++);
}
},seconds/st);
}
function pause(){
isPaused = true;
}
function play(){
clearInterval(inter);
var d1 = document.getElementById("date1").value;
document.getElementById("date").value = d1;
startSlider(dateDifference(), document.getElementById("time").value);
isPaused = false;
}
function stop(){
eventNum = 0;
i = 0;
clearInterval(inter);
var d1 = document.getElementById("date1").value;
document.getElementById("date").value = d1;
$("#slider").slider("value",0);
}
function set(){
i=$("#slider").slider("value")+1;
$("#slider").slider("value",i++);
}
function dateDifference(){
var d1 = new Date(document.getElementById("date1").value);
var d2 = new Date(document.getElementById("date2").value);
var timeDiff = Math.abs(d2.getTime() - d1.getTime());
return difDays = Math.ceil(timeDiff/(1000*3600*24));
}
function setDate(n){
var d1 = new Date(document.getElementById("date1").value);
d1.setDate(d1.getDate() + n);
var d2 = d1.toISOString().substr(0,10);
document.getElementById("date").value = d2;
}
$(function() {
$("#date1").on("change",function(){
var selected = $(this).val();
document.getElementById("date2").setAttribute("min",selected);
});
});
$("slider").mouseup(function(){
$(this).after("Mouse button released.");
});
</script>
</head>
<body>
<div>
<label for="from">From</label>
<input type="date" name="date1" id="date1" >
<label for="to">to</label>
<input type="date" name="date2" id="date2" min="">
<label for="time">Time</label>
<input type="text" name="time" id="time">
<input type="text" name="date" id="date">
</div>
<br>
<div id="slider" ></div>
<br>
<button onclick="pause()">pause</button>
<button onclick="play()">play</button>
<button onclick="stop()">stop</button>
</body>
</html>

How set the value of an input element? [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 9 years ago.
This script counts the days between two dates and shows the result on a span element:
<span id="result"></span>
But instead I want to show the result as value of an input element:
<input name="name" type="text" id="name" value="i want count days here " />
How can I do this?
This is the complete code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-datepicker {font-size:11px;}
</style>
<script>
$(function() {
$( "#from" ).datepicker({
onSelect: calculate
});
});
$(function() {
$( "#to" ).datepicker({
onSelect: calculate
});
});
</script>
</head>
<body>
<form class="formwhite">
<table>
<tr><td>From:</td><td><input type="text" id="from" onKeyUp="calculate();" /> </td></tr>
<tr><td>To:</td><td><input type="text" id="to" onKeyUp="calculate();" /></td></tr>
</table>
</form>
<span id="result"></span>
<script>
var calculate = function() {
var from = document.getElementById("from").value;
var fromdate = from.slice(3, 5);
fromdate = parseInt(fromdate);
var frommonth = from.slice(0, 2);
frommonth = parseInt(frommonth);
var fromyear = from.slice(6, 10);
fromyear = parseInt(fromyear);
var to = document.getElementById("to").value;
var todate = to.slice(3, 5);
todate = parseInt(todate);
var tomonth = to.slice(0, 2);
tomonth = parseInt(tomonth);
var toyear = to.slice(6, 10);
toyear = parseInt(toyear);
var oneDay = 24*60*60*1000;
var firstDate = new Date(fromyear,frommonth,fromdate);
var secondDate = new Date(toyear,tomonth,todate);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
if (diffDays)
document.getElementById("result").innerHTML=diffDays;
}
</script>
</body>
</html>
So you're asking the question: "How do I get a value from one field and set it in another?" You want http://api.jquery.com/val/ :
$("#name").val($("#result").val());
$("#result").val() gets whatever value the element with id result has.
$("#name").val(value) sets the value of the element with id name
Or, simply add (or replace) the line
document.getElementById("name").value = diffDays;
in the same if block as where you have
document.getElementById("result").innerHTML = diffDays;
Here's your entire <script> block, with my one line added:
<script>
var calculate = function() {
var from = document.getElementById("from").value;
var fromdate = from.slice(3, 5);
fromdate = parseInt(fromdate);
var frommonth = from.slice(0, 2);
frommonth = parseInt(frommonth);
var fromyear = from.slice(6, 10);
fromyear = parseInt(fromyear);
var to = document.getElementById("to").value;
var todate = to.slice(3, 5);
todate = parseInt(todate);
var tomonth = to.slice(0, 2);
tomonth = parseInt(tomonth);
var toyear = to.slice(6, 10);
toyear = parseInt(toyear);
var oneDay = 24*60*60*1000;
var firstDate = new Date(fromyear,frommonth,fromdate);
var secondDate = new Date(toyear,tomonth,todate);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
if (diffDays) /* THE NEW STUFF IS RIGHT HERE*/ {
document.getElementById("result").innerHTML=diffDays;
document.getElementById("name").value=diffDays;
} // THE NEW STUFF ENDS HERE
}
</script>

Categories