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

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>

Related

Javascript Warp Time with Warp js

I'm working on a project where I need to manipulate time speed forward and backward. This module seems like what I need but I can't get it working:
https://github.com/mattbradley/warpjs/blob/master/README.md
Any help appreciated
<html>
<head>
</head>
<body>
<script src="jquery.min.js"></script>
<script src="warp.js"></script>
<div id="container"></div>
<span id="info"></span><br>
<span id="time"></span>
<span id="time2"></span>
<script>
setInterval(function() {
var now = new Date;
now = Date.warp.clock(true);
//now = Date.warp.speed(2); // DOESNT WORK?
var dateD = [now.getMonth() + 1,now.getDate(),now.getFullYear()];
var dateE = [now.getHours(),now.getMinutes(),now.getSeconds()];
var MDY = dateD.join("/");
var HMS = dateE.join(":");
time.innerHTML = (MDY);
time2.innerHTML = (HMS);
}, 20);
</script>
</body>
</html>
The wrap is a static method, it doesn't return any value(undefined is returned)
setInterval(function() {
Date.warp.speed(3);
var now = new Date;
var dateD = [now.getMonth() + 1, now.getDate(), now.getFullYear()];
var dateE = [now.getHours(), now.getMinutes(), now.getSeconds()];
var MDY = dateD.join("/");
var HMS = dateE.join(":");
time.innerHTML = (MDY);
time2.innerHTML = (HMS);
}, 1000);
Demo: Fiddle

Including created javascript files in html

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.

Javascript MomentJs wrong output

1.
Ok, for the first question I have a question about Moment. It doesn't calculate the time right(I think?)
This is my script:
function CalculateTime() {
try {
var originalStartTime = $('#startTime').val(),
originalEndTime = $('#endTime').val(),
originalBreakTime = $('#breakTime').val();
// breaking hours and minutes. needed format: HH:mm
var startHours = originalStartTime.substring(0, 2).replace(':', ''),
startMinutes = originalStartTime.substring(3, 5),
endHours = originalEndTime.substring(0, 2).replace(':', ''),
endMinutes = originalEndTime.substring(3, 5);
// momentJs variables
var mStart = moment().hour(startHours).minute(startMinutes),
mEnd = moment().hour(endHours).minute(endMinutes),
mBreak = moment.duration(originalBreakTime);
var result = moment( mEnd - mStart - mBreak).format('HH:mm');
$('#workedHours').val(result + " timmar");
} catch (err) {
$('#workedHours').val(err);
}
startTime: 07:00, endTime: 16:00, breakTime 00.00
That will result with workedHours being 10.00.
This is from the chrome console:
You need to use the subtract method
function CalculateTime() {
try {
var originalStartTime = $('#startTime').val(),
originalEndTime = $('#endTime').val(),
originalBreakTime = $('#breakTime').val();
// breaking hours and minutes. needed format: HH:mm
var startHours = originalStartTime.substring(0, 2).replace(':', ''),
startMinutes = originalStartTime.substring(3, 5),
endHours = originalEndTime.substring(0, 2).replace(':', ''),
endMinutes = originalEndTime.substring(3, 5),
breakHours = originalBreakTime.substring(0, 2).replace(':', ''),
breakMinutes = originalBreakTime.substring(3, 5);
// momentJs variables
var mStart = moment().hour(startHours).minute(startMinutes),
mEnd = moment().hour(endHours).minute(endMinutes),
mBreak = moment.duration(breakHours * 60 + +breakMinutes, 'minutes');
var result = mEnd.subtract(mStart).subtract(mBreak).format('HH:mm');
$('#workedHours').val(result + " timmar");
} catch (err) {
$('#workedHours').val(err);
}
}
CalculateTime();
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="startTime" value="07:00" />
<input id="endTime" value="16:00" />
<input id="breakTime" value="00.30" />
<input id="workedHours" />
I think a more momentjs way is
function CalculateTime() {
try {
var originalStartTime = $('#startTime').val(),
originalEndTime = $('#endTime').val(),
originalBreakTime = $('#breakTime').val();
// momentJs variables
var mStart = moment(originalStartTime, 'HH:mm'),
mEnd = moment(originalEndTime, 'HH:mm'),
mBreak = moment.duration(originalBreakTime);
var result = mEnd.subtract(mStart).subtract(mBreak).format('HH:mm');
$('#workedHours').val(result + " timmar");
} catch (err) {
$('#workedHours').val(err);
}
}
CalculateTime();
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="startTime" value="07:00" />
<input id="endTime" value="16:00" />
<input id="breakTime" value="00:30" />
<input id="workedHours" />

javaScript code working in a seperate file but not part of a bigger file

I am making a simple Goal-traking completely offline HTML5 app using localStorage.
The problem that I am facing is, that, Retrieving JSON data is working completely fine in a separate file but not when put together as a part of a bigger system.
I would have kept it in a seperate file and would have stopped worrying about it, but I can't do that because of same-origin policy.
Here is the code that's working fine as a seperate file:
<HTML>
<HEAD>
</HEAD>
<BODY>
<script type="text/javascript">
window.onload = function(){
// setup
var goal = "CN";
var date2 = new Date();
var diff = 0;
var active = true;http://jsfiddle.net/#save
var data = '{"goals": [{"goal":"' + goal + '","duedate":"'
+ date2 + '","noofdays":"' + diff + '","active":"'
+ active + '"}]}';
localStorage.setItem("goals",data);
// test
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
for (i=0; i<goalsObj.goals.length; i++) {
if(goal==goalsObj.goals[i].goal) {
document.body.appendChild(document.createTextNode(
"The goal is " + JSON.stringify(goalsObj.goals[i])));
}
}
}
</script>
</BODY>
</HTML>
and now here is the code that is supposed to work, as all of it's different parts are working fine, all the syntax is correct, but still it is giving absolutely no output:
<HTML>
<HEAD>
</HEAD>
<BODY>
<script type="text/javascript">
function save()
{
//Get data from the form
var goal = document.getElementById("goal").value; //Get 'goal' from form
var date2 = document.getElementById("date2").value; //Get 'duedate' from the form
var active = document.getElementById("active").value; //Get 'active' from form
//Calculating the number of days remaining
var date1 = new Date(); //Current Date and Time
var dd = date1.getDate(); //Current Date
var mm = date1.getMonth()+1; //January is 0!
var yyyy = date1.getFullYear(); //Current Year
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} date1 = mm+'/'+dd+'/'+yyyy; //Parsing the date to the required format
var diff = Math.floor(( Date.parse(date2) - Date.parse(date1) ) / 86400000); //Calculate no. of days remaining
if (localStorage.getItem('gcount') === null) {
localStorage.setItem('gcount', "1");
var data = '{"goals":[{"goal":"'+goal+'","duedate":"'+date2+'","noofdays":"'+diff+'","active":"'+active+'"}]}';
localStorage.setItem("goals",data);
//document.getElementById("temp").innerHTML="first";
}
else{
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
var goal = "CN"
var data = { "goal": goal, "duedate": date2, "noofdays": diff, "active": active};
goalsObj.goals.push(data);
localStorage.setItem("goals", JSON.stringify(goalsObj));
}
}
function load(){
/* // setup
var goal = "CN";
var date2 = new Date();
var diff = 0;
var active = true;http://jsfiddle.net/#save
var data = '{"goals": [{"goal":"' + goal + '","duedate":"'
+ date2 + '","noofdays":"' + diff + '","active":"'
+ active + '"}]}';
localStorage.setItem("goals",data); */
// test
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
for (i=0; i<goalsObj.goals.length; i++) {
if(goal==goalsObj.goals[i].goal) {
document.getElementById("duedate").innerHTML=goalsObj.goals[i].duedate;
document.getElementById("noofdays").innerHTML=goalsObj.goals[i].noofdays;
document.getElementById("active").innerHTML=goalsObj.goals[i].active;
// document.body.appendChild(document.createTextNode("The goal is " + JSON.stringify(goalsObj.goals[i])));
}
}
}
</script>
<form name="input" onsubmit="save(); return false;">
<label>Goal: </label> <input type="text" name="goal" id="goal"><br>
<label>Due Date: </label> <input type="date" name="date2" id="date2"></span><br>
<label>Active: </label><br>
<input type="radio" name="active" id="active" value="Future">Future <br>
<input type="radio" name="active" id="active" value="Present">Present <br> <br>
<!-- Submit button to submit the form -->
<input type="submit" value="submit">
</form>
<form name="load" onsubmit="load(); return false;">
<label>Goal: </label> <input type="text" name="goal" id="goal"><br>
<input type="submit" value="submit">
<p id="temp"></p>
<p id="temp1"></p>
<p id="temp2"></p>
<p id="temp3"></p>
<p id="temp4"></p>
<p id="temp5"></p>
<p id="temp6"></p>
<p id="temp7"></p>
<p id="temp8"></p>
<p id="duedate"></p>
<p id="noofdays"></p>
<p id="active"></p>
</BODY>
</HTML>
I am getting the error that object is not a function. I have tried all other similar questions on StackOverflow and nothing worked.
What's wrong? What should I do?
You are using the same id for multiple different elements.
Also, try using IndexedDB instead of localStorage.

output my javascript variable in a div

i want to output the javascript dayz variable into the results div, but its not outputting anything, when i try alert(dayz) after the calculation it does, but i want it to output the dayz variable the html.
..help
<html>
<head>
<title>My first JavaScript page</title>
<script type="text/javascript">
var calculation = function(){
//days
var hours = document.getElementById("hours_id").value;
var d = 10000/hours;
var da = 1000%hours;
var dayz = d.toFixed(0);
dayz = parseInt(dayz, 10);
dayz = dayz + da;
//years
var years = days/365;
years = years.toFixed(2);
//weeks
var weeks = days/7;
weeks = weeks.toFixed(2);
};
document.getElementById('results').innerHTML=dayz;
</script>
</head>
<body>
<form name="input">
<input type="text" id="hours_id" name="hours_id">
<input type="button" id="submit" value="calculate" onClick="calculation()">
</form>
<div id="results"> </div>
</body>
</html>
Try this
function calculation(){
//days
var hours = document.getElementById("hours_id").value;
var d = 10000/hours;
var da = 1000%hours;
var dayz = d.toFixed(0);
dayz = parseInt(dayz, 10);
dayz = dayz + da;
//years
var years = dayz/365;
years = years.toFixed(2);
//weeks
var weeks = dayz/7;
weeks = weeks.toFixed(2);
document.getElementById('results').innerHTML=dayz;
};
DEMO
Put the following statement inside the function definition:
document.getElementById('results').innerHTML = dayz;
like this:
var calculation = function () {
//days
var hours = document.getElementById("hours_id").value;
var d = 10000 / hours;
var da = 1000 % hours;
var dayz = d.toFixed(0);
dayz = parseInt(dayz, 10);
dayz = dayz + da;
//years
var years = dayz / 365;
years = years.toFixed(2);
//weeks
var weeks = dayz / 7;
weeks = weeks.toFixed(2);
document.getElementById('results').innerHTML = dayz;
};

Categories