Getting Current age by user input javascript - javascript

I want my user when they click on “view age” button to calculate there age from there input, but i couldn't figure it out. I got the user to view there birth year when they click on the but.
Here is my HTML Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="birth">
<h2>What month were you born?</h2><input name="birthMonth" type="text" size="20">
<h2>What day was you born?</h2><input name="birthday" type="text" size="20">
<h2>Your birth year?</h2> <input name="birthYear" type="text" size="20">
</form>
<button onclick="outputbirth()">Submit</button>
<button onclick="submitBday()">View Age</button>
<p id="output"></p>
<p id="age"></p>
<script type="text/javascript" src="scripts/scripts.js"></script>
</body>
</html>
JavaScript Code, function submitBday is the button on the html document:
function outputbirth() {
// Getting the form id "birth"
var x = document.getElementById("birth");
var text = "";
// Getting the users input values of Month, Day, Year.
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + " ";
}
// This is going to print out the result on output id in the html document
document.getElementById("output").innerHTML = text;
}
function submitBday() {
}

You already concatenated a string from the input fields. So what you want to do to calculate the age is to construct a date object from the input fields. Just collect the input fields like you did before in a loop, but do not separate the values by an empty space but use a comma.
var bDay += x.elements[i].value + ",";
Then pass the bDay to a new date object.
var start = new Date(bDay);
Now subtract the just created date from now.
var elapsed = Date.now() - start;
This will give you the age in milliseconds. To calculate the years from milliseconds you could do this.
var age = Math.floor(((((elapsed / 1000) / 60) / 60) /24) / 365);
This will give you the age in years. If you want to find out more about the JS date object check out the moz dev network page on Date.
I left a snipped for you. Have fun.
function submitBday() {
var now = Date.now(),
x = document.getElementById("birth"),
bDay = "",
start,
elapsed,
age;
for (i = 0; i < x.length; i++) {
bDay += x.elements[i].value + ",";
}
start = new Date(bDay);
elapsed = now - start;
age = Math.floor(((((elapsed / 1000) / 60) / 60) /24) / 365);
document.getElementById("age").innerHTML = "You are " + age + " years young.";
}
<form id="birth">
<h2>What month were you born?</h2><input name="birthMonth" type="text" size="20">
<h2>What day was you born?</h2><input name="birthday" type="text" size="20">
<h2>Your birth year?</h2> <input name="birthYear" type="text" size="20">
</form>
<button onclick="submitBday()">View Age</button>
<p id="age"></p>

Related

Display second prompt if the first prompt is not TRUE

I have a problem when i try to display new prompt, i use loop but it will display both my prompt. Here is my code and i really need help
<body>
<p id="age" style="font-weight: bold"></p>
<button onclick=" notify()">Try it</button>
<script>
function notify(){
var age = document.getElementById("age").value;
var age = prompt("Enter Your birth year:");// This is the first prompt
const year = new Date().getFullYear();
if (age != null) {
document.getElementById("age").innerHTML =
"Your " + age + " is so beautiful"; // If user enter birth year < current year will display this
}
do {
age = prompt("Re-enter your birth year:"); // Ortherwise, this will display and they need to enter until birth year < current year
} while (age > year && age != null);
var tuoi = year - age;// This is just calculate user'age, for example if the user enter 2000 will display user'age is 22
document.getElementById("age").innerHTML =
"Tuổi " + tuoi + " này đẹp đó";
}
</script>
</body>
your code has several issues and does some things which do not make total sense to me, but I think you want something like this:
<body>
<p id="age" style="font-weight: bold"></p>
<button onclick=" notify()">Try it</button>
<script>
function notify() {
const year = new Date().getFullYear();
var birth_year = parseInt(prompt("Enter Your birth year:")); // This is the first prompt
if (!isNaN(birth_year) && birth_year < year) {
document.getElementById("age").innerHTML =
"Your " + birth_year + " is so beautiful"; // If user enter birth year < current year will display this
} else {
do {
birth_year = parseInt(prompt("Enter Your birth year:")); // Ortherwise, this will display and they need to enter until birth year < current year
} while (isNaN(parseInt(birth_year)) || birth_year >= year);
var tuoi = year - age; // This is just calculate user'age, for example if the user enter 2000 will display user'age is 22
document.getElementById("age").innerHTML =
"Tuổi " + birth_year + " này đẹp đó";
}
}
</script>
</body>
You simply forgot a part of your if condition.
Change if (age != null) to if (age != null && age < year) and it will work as you expect it. Don't forget the case if age == year.

How to set time value from one textbox to another wicked time picker?

I need to set the time value in time picker which I'm putting in another text box.
like if I put 10:30 PM in my text box then on button click in another text box which have wicked timepicker in it
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<link rel="stylesheet" href="stylesheets/wickedpicker.css">
<script src="src/wickedpicker.js"></script>
<input type="text" class="input" id="time"/><br>
<input type="text" class="input" id="time1"/><br>
<input type="button" value="Show" id="btn"/>
in jquery I tried this-
$("#time").wickedpicker();
$("#btn").click(function(){
var val=$("#time1").val();
$("#time").wickedpicker("setTime",val);
$("#time1").wickedpicker("setTime",val);
alert("selected time is " + val);
});
I did the same with date picker and it worked so I thought it would work with this but its no use even alert is not working, its saying value undefine.
Below code include the modification of wicked picker js in order to change and update picker value.
/**
* wickedpicker v0.4.1 - A simple jQuery timepicker.
* Copyright (c) 2015-2016 Eric Gagnon - http://github.com/wickedRidge/wickedpicker
* License: MIT
*
* Modified to allow changing the time.
* Example:
* var options = {now: "12:35"};
* var myPicker = $('.timepicker').wickedpicker(options);
*
* myPicker.wickedpicker('setTime', 0, "14:00"); // 0 is the index of the timepicker. Use 0 if only one
*/
!function($,window,document){"use strict";"function"!=typeof String.prototype.endsWith&&(String.prototype.endsWith=function(e){return e.length>0&&this.substring(this.length-e.length,this.length)===e});var isMobile=function(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)},today=new Date,pluginName="wickedpicker",defaults={now:today.getHours()+":"+today.getMinutes(),twentyFour:!1,upArrow:"wickedpicker__controls__control-up",downArrow:"wickedpicker__controls__control-down",close:"wickedpicker__close",hoverState:"hover-state",title:"Timepicker",showSeconds:!1,timeSeparator:" : ",secondsInterval:1,minutesInterval:1,beforeShow:null,afterShow:null,show:null,clearable:!1,closeOnClickOutside:!0,onClickOutside:function(){}};function Wickedpicker(e,t){this.element=$(e),this.options=$.extend({},defaults,t),this.element.addClass("hasWickedpicker"),this.element.attr("onkeypress","return false;"),this.element.attr("aria-showingpicker","false"),this.createPicker(),this.timepicker=$(".wickedpicker"),this.up=$("."+this.options.upArrow.split(/\s+/).join(".")),this.down=$("."+this.options.downArrow.split(/\s+/).join(".")),this.separator=$(".wickedpicker__controls__control--separator"),this.hoursElem=$(".wickedpicker__controls__control--hours"),this.minutesElem=$(".wickedpicker__controls__control--minutes"),this.secondsElem=$(".wickedpicker__controls__control--seconds"),this.meridiemElem=$(".wickedpicker__controls__control--meridiem"),this.close=$("."+this.options.close.split(/\s+/).join("."));var i=this.timeArrayFromString(this.options.now);this.options.now=new Date(today.getFullYear(),today.getMonth(),today.getDate(),i[0],i[1],i[2]),this.selectedHour=this.parseHours(this.options.now.getHours()),this.selectedMin=this.parseSecMin(this.options.now.getMinutes()),this.selectedSec=this.parseSecMin(this.options.now.getSeconds()),this.selectedMeridiem=this.parseMeridiem(this.options.now.getHours()),this.setHoverState(),this.attach(e),this.setText(e)}$.extend(Wickedpicker.prototype,{showPicker:function(e){"function"==typeof this.options.beforeShow&&this.options.beforeShow(e,this.timepicker);var t=$(e).offset();if($(e).attr({"aria-showingpicker":"true",tabindex:-1}),this.setText(e),this.showHideMeridiemControl(),this.getText(e)!==this.getTime()){var i=this.getText(e),s=/\s\w\w$/.test(i)?i.substr(-2,2):null,o=i.replace(/\s\w\w$/,"").split(this.options.timeSeparator),n={};n.hours=o[0],n.minutes=o[1],this.options.showSeconds?(n.seconds=o[2],n.meridiem=s):n.meridiem=s,this.setTime(n)}this.timepicker.css({"z-index":this.element.css("z-index")+1,position:"absolute",left:t.left,top:t.top+$(e)[0].offsetHeight}).show(),"function"==typeof this.options.show&&this.options.show(e,this.timepicker),this.handleTimeAdjustments(e)},hideTimepicker:function(e){var t;this.timepicker.hide(),"function"==typeof this.options.afterShow&&this.options.afterShow(e,this.timepicker),function(){var e=$.Deferred();return $('[aria-showingpicker="true"]').attr("aria-showingpicker","false"),e.promise()}().then((t=0,void setTimeout(function(){$('[aria-showingpicker="false"]').attr("tabindex",t)},400)))},createPicker:function(){if(0===$(".wickedpicker").length){var e='<div class="wickedpicker"><p class="wickedpicker__title">'+this.options.title+'<span class="wickedpicker__close"></span></p><ul class="wickedpicker__controls"><li class="wickedpicker__controls__control"><span class="'+this.options.upArrow+'"></span><span class="wickedpicker__controls__control--hours" tabindex="-1">00</span><span class="'+this.options.downArrow+'"></span></li><li class="wickedpicker__controls__control--separator"><span class="wickedpicker__controls__control--separator-inner">:</span></li><li class="wickedpicker__controls__control"><span class="'+this.options.upArrow+'"></span><span class="wickedpicker__controls__control--minutes" tabindex="-1">00</span><span class="'+this.options.downArrow+'"></span></li>';this.options.showSeconds&&(e+='<li class="wickedpicker__controls__control--separator"><span class="wickedpicker__controls__control--separator-inner">:</span></li><li class="wickedpicker__controls__control"><span class="'+this.options.upArrow+'"></span><span class="wickedpicker__controls__control--seconds" tabindex="-1">00</span><span class="'+this.options.downArrow+'"></span> </li>'),e+='<li class="wickedpicker__controls__control"><span class="'+this.options.upArrow+'"></span><span class="wickedpicker__controls__control--meridiem" tabindex="-1">AM</span><span class="'+this.options.downArrow+'"></span></li></ul></div>',$("body").append(e),this.attachKeyboardEvents()}},showHideMeridiemControl:function(){!1===this.options.twentyFour?$(this.meridiemElem).parent().show():$(this.meridiemElem).parent().hide()},showHideSecondsControl:function(){this.options.showSeconds?$(this.secondsElem).parent().show():$(this.secondsElem).parent().hide()},attach:function(e){var t=this;this.options.clearable&&t.makePickerInputClearable(e),$(e).attr("tabindex",0),$(e).on("click focus",function(e){$(t.timepicker).is(":hidden")&&(t.showPicker($(this)),window.lastTimePickerControl=$(this),$(t.hoursElem).focus())});var i=function(e){if($(t.timepicker).is(":visible")){if($(e.target).is(t.close))t.hideTimepicker(window.lastTimePickerControl);else if($(e.target).closest(t.timepicker).length||$(e.target).closest($(".hasWickedpicker")).length)e.stopPropagation();else{if("function"==typeof t.options.onClickOutside?t.options.onClickOutside():console.warn("Type of onClickOutside must be a function"),!t.options.closeOnClickOutside)return;t.hideTimepicker(window.lastTimePickerControl)}window.lastTimePickerControl=null}};$(document).off("click",i).on("click",i)},attachKeyboardEvents:function(){$(document).on("keydown",$.proxy(function(e){switch(e.keyCode){case 9:"hasWickedpicker"!==e.target.className&&$(this.close).trigger("click");break;case 27:$(this.close).trigger("click");break;case 37:e.target.className!==this.hoursElem[0].className?$(e.target).parent().prevAll("li").not(this.separator.selector).first().children()[1].focus():$(e.target).parent().siblings(":last").children()[1].focus();break;case 39:e.target.className!==this.meridiemElem[0].className?$(e.target).parent().nextAll("li").not(this.separator.selector).first().children()[1].focus():$(e.target).parent().siblings(":first").children()[1].focus();break;case 38:$(":focus").prev().trigger("click");break;case 40:$(":focus").next().trigger("click")}},this))},setTime:function(e){this.setHours(e.hours),this.setMinutes(e.minutes),this.setMeridiem(e.meridiem),this.options.showSeconds&&this.setSeconds(e.seconds)},getTime:function(){return[this.formatTime(this.getHours(),this.getMinutes(),this.getMeridiem(),this.getSeconds())]},setHours:function(e){var t=new Date;t.setHours(e);var i=this.parseHours(t.getHours());this.hoursElem.text(i),this.selectedHour=i},getHours:function(){var e=new Date;return e.setHours(this.hoursElem.text()),e.getHours()},parseHours:function(e){return!1===this.options.twentyFour?(e+11)%12+1:e<10?"0"+e:e},setMinutes:function(e){var t=new Date;t.setMinutes(e);var i=t.getMinutes(),s=this.parseSecMin(i);this.minutesElem.text(s),this.selectedMin=s},getMinutes:function(){var e=new Date;return e.setMinutes(this.minutesElem.text()),e.getMinutes()},parseSecMin:function(e){return(e<10?"0":"")+e},setMeridiem:function(e){var t="";void 0===e?t="PM"===this.getMeridiem()?"AM":"PM":t=e;this.meridiemElem.text(t),this.selectedMeridiem=t},getMeridiem:function(){return this.meridiemElem.text()},setSeconds:function(e){var t=new Date;t.setSeconds(e);var i=t.getSeconds(),s=this.parseSecMin(i);this.secondsElem.text(s),this.selectedSec=s},getSeconds:function(){var e=new Date;return e.setSeconds(this.secondsElem.text()),e.getSeconds()},parseMeridiem:function(e){return e>11?"PM":"AM"},handleTimeAdjustments:function(e){var t=0;$(this.up).add(this.down).off("mousedown click touchstart").on("mousedown click",{Wickedpicker:this,input:e},function(e){if(1!=e.which)return!1;var i=this.className.indexOf("up")>-1?"+":"-",s=e.data;"mousedown"==e.type?t=setInterval($.proxy(function(e){e.Wickedpicker.changeValue(i,e.input,this)},this,{Wickedpicker:s.Wickedpicker,input:s.input}),200):s.Wickedpicker.changeValue(i,s.input,this)}).bind("mouseup touchend",function(){clearInterval(t)})},changeValue:function(operator,input,clicked){var target="+"===operator?clicked.nextSibling:clicked.previousSibling,targetClass=$(target).attr("class");targetClass.endsWith("hours")?this.setHours(eval(this.getHours()+operator+1)):targetClass.endsWith("minutes")?this.setMinutes(eval(this.getMinutes()+operator+this.options.minutesInterval)):targetClass.endsWith("seconds")?this.setSeconds(eval(this.getSeconds()+operator+this.options.secondsInterval)):this.setMeridiem(),this.setText(input)},setText:function(e){$(e).val(this.formatTime(this.selectedHour,this.selectedMin,this.selectedMeridiem,this.selectedSec)).change()},getText:function(e){return $(e).val()},formatTime:function(e,t,i,s){var o=e+this.options.timeSeparator+t;return this.options.twentyFour&&(o=e+this.options.timeSeparator+t),this.options.showSeconds&&(o+=this.options.timeSeparator+s),!1===this.options.twentyFour&&(o+=" "+i),o},setHoverState:function(){var e=this;isMobile()||$(this.up).add(this.down).add(this.close).hover(function(){$(this).toggleClass(e.options.hoverState)})},makePickerInputClearable:function(e){$(e).wrap('<div class="clearable-picker"></div>').after("<span data-clear-picker>×</span>"),$("[data-clear-picker]").on("click",function(e){$(this).siblings(".hasWickedpicker").val("")})},timeArrayFromString:function(e){if(e.length){var t=e.split(":");return t[2]=t.length<3?"00":t[2],t}return!1},_time:function(){var e=$(this.element).val();return""===e?this.formatTime(this.selectedHour,this.selectedMin,this.selectedMeridiem,this.selectedSec):e},_setTime:function(e){this.options.now=e;var t=this.timeArrayFromString(this.options.now);this.options.now=new Date(today.getFullYear(),today.getMonth(),today.getDate(),t[0],t[1],t[2]),this.selectedHour=this.parseHours(this.options.now.getHours()),this.selectedMin=this.parseSecMin(this.options.now.getMinutes()),this.selectedSec=this.parseSecMin(this.options.now.getSeconds()),this.selectedMeridiem=this.parseMeridiem(this.options.now.getHours()),this.setText(this.element);var i=$(this.element).val();return""===i?this.formatTime(this.selectedHour,this.selectedMin,this.selectedMeridiem,this.selectedSec):i},_hide:function(){this.hideTimepicker(this.element)}}),$.fn[pluginName]=function(e,t,i){return $.isFunction(Wickedpicker.prototype["_"+e])?$(this).hasClass("hasWickedpicker")?"setTime"===e?void 0!==t?$.data($(this)[t],"plugin_"+pluginName)._setTime(i):$.data($(this)[0],"plugin_"+pluginName)._setTime(i):void 0!==t?$.data($(this)[t],"plugin_"+pluginName)["_"+e]():$.data($(this)[0],"plugin_"+pluginName)["_"+e]():void 0:this.each(function(){$.data(this,"plugin_"+pluginName)||$.data(this,"plugin_"+pluginName,new Wickedpicker(this,e))})}}(jQuery,window,document);
$(document).ready(function() {
var timepicker = $("#time").wickedpicker();
$("#btn").click(function(){
var time = timepicker.wickedpicker('time');
time = time.replace(' : ', ' ');
var h = time.split(' ')[0];
var m = time.split(' ')[1];
var ampm = time.split(' ')[2];
if (ampm == 'PM') {
h = parseInt(h) + 12;
}
var options2 = {
now: h+':'+m,
};
var time1 = $("#time1").wickedpicker(options2);
time1.wickedpicker('setTime',0, h+':'+m)
});
});
<link href="https://www.jqueryscript.net/demo/Minimal-jQuery-Timer-Picker-Plugin-Wickedpicker/stylesheets/wickedpicker.css" rel="stylesheet"/>
<input type="text" class="input" id="time"/><br>
<input type="text" class="input" id="time1"/><br>
<input type="button" value="Show" id="btn"/><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
1) Use wickedpicker('time') to get time value instead.
2) Convert time in 24 hours format before assigning the time value.
$('#time1').wickedpicker();
$('button').on('click', function() {
// get time form time1
var t = ($('#time1').wickedpicker('time'));
// convert to 24 hours format
t = t.replace(' : ', ' ');
var h = t.split(' ')[0];
var m = t.split(' ')[1];
var ampm = t.split(' ')[2];
if (ampm == 'PM') {
h = parseInt(h) + 12;
}
// set time to time2
$('#time2').wickedpicker({now: h+':'+m});
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/wickedpicker#0.4.3/dist/wickedpicker.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/wickedpicker#0.4.3/dist/wickedpicker.min.js"></script>
Time 1: <input type="text" class="time" id="time1"><br>
Time 2: <input type="text" class="time" id="time2"><br>
<button>Click Me</button>
I used the following code to set the time (timeTokens is array consisting of hour and minute):
var setTimePicker = function (timeTokens) {
$('.wickedpicker__controls__control--hours').text(timeTokens[0]);
$('.wickedpicker__controls__control--minutes').text(timeTokens[1]);
wickedpicker.data('plugin_wickedpicker').selectedHour = timeTokens[0];
wickedpicker.data('plugin_wickedpicker').selectedMin = timeTokens[1];
}

javascript / html won't display result of calculation

I'm trying to create a heart rate zone calculator but it won't display the result of the calculation. I am new to javascript and html (coming from a java background) so any help and constructive criticism with that in mind is appreciated!
<html>
<head>
<title>BMI Calculator</title>
<script type="text/javascript">
function CalculateBMI()
{
//Obtain user inputs
var Intensity = Number(document.getElementById("Intensity").value);
var select_intensity = document.getElementById("select_intensity").value;
var Age = Number(document.getElementById("Age").value);
//Perform calculation based on intensity
if (select_intensity == "Moderate") {
var output = (220-Age)*.5;
var output2 = (220-Age)*.7;
}
if (select_intensity == "High Intensity") {
output = (220 - Age) * .7;
output2 = (220 - Age) * .85;
}
//Display result of calculation
document.getElementById("output").innerHTML=output " to " output2;
}
</script>
</head>
<body>
<h1>Heart Rate Zone Calculator</h1>
<p>Select Your Workout Intensity: <select type="multiple" id="Intensity">
<option value="Moderate"selected="selected">Moderate</option>
<option value="High Intensity">High Intensity</option>
</select>
</p>
<p>Enter your age: <input type="text" id="Age"/>
</p>
<input type="submit" value="Calculate Target Heart Rate" onclick="CalculateBMI();">
<h1>Your Target Heart Rate Zone Is: <span id="output" >?</span></h1>
</body>
You have a couple of issues with your Javascript:
1) You have 2 intensity variables:
var Intensity = Number(document.getElementById("Intensity").value);
var select_intensity = document.getElementById("select_intensity").value;
Intensity refers to the correct element, but all of your code seems to only reference the select_intensity variable. Do this instead:
var select_intensity = document.getElementById("Intensity").value;
2) You forgot to place + around the " to " string for concatenation.
document.getElementById("output").innerHTML=output + " to " + output2;
Fixing both of those issues should cause it to work.
Remove
var Intensity = Number(document.getElementById("Intensity").value);
and change
var select_intensity = document.getElementById("Intensity").value;
to
var select_intensity = document.getElementById("select_intensity ").value;
Also change this
document.getElementById("output").innerHTML=output + " to " + output2;
This is finally how your code should look like
<html>
<head>
<title>BMI Calculator</title>
<script type="text/javascript">
function CalculateBMI()
{
//Obtain user inputs
//var Intensity = Number(document.getElementById("Intensity").value);
var select_intensity = document.getElementById("Intensity").value;
var Age = Number(document.getElementById("Age").value);
//Perform calculation based on intensity
if (select_intensity == "Moderate") {
var output = (220-Age)*.5;
var output2 = (220-Age)*.7;
}
if (select_intensity == "High Intensity") {
output = (220 - Age) * .7;
output2 = (220 - Age) * .85;
}
//Display result of calculation
document.getElementById("output").innerHTML=output + " to " + output2;
}
</script>
</head>
<body>
<h1>Heart Rate Zone Calculator</h1>
<p>Select Your Workout Intensity: <select type="multiple" id="Intensity">
<option value="Moderate"selected="selected">Moderate</option>
<option value="High Intensity">High Intensity</option>
</select>
</p>
<p>Enter your age: <input type="text" id="Age"/>
</p>
<input type="submit" value="Calculate Target Heart Rate" onclick="CalculateBMI();">
<h1>Your Target Heart Rate Zone Is: <span id="output" >?</span></h1>
</body>
smaili's answer sums it up. I'd just like to add that as a new javascript programmer, you'll wanna be familiar with console.log() and F12 in your browser (unless you have a full-on JS dev IDE).

document.getElementById.innerHTML not working

document.getElementById gets the element (i.e p tag) but as soon as
it writes in it the content disappears. There is no error on console but whatever is written within p tag disappears as soon as anything is written onto the p tag.
I can't find any reason for it not working also i'am not allowed to use php for accepting form inputs.
var d=new Date();
var cday=d.getDay();
var cmonth=d.getMonth();
var cyear=d.getFullYear();
var day,month,year,dage,mage,yage;
function getDOB() {
var DOB = new Date(document.getElementById("DOB").value);
year = DOB.getFullYear();
month = DOB.getMonth();
day = DOB.getDay();
}
document.getElementById("inp").onclick = function execute() {
getDOB();
yage = cyear - year;
if (cmonth >= month) {
mage = cmonth - month;
} else {
mage = 12 - (month - cmonth);
yage = yage - 1;
}
if (cday >= day) {
dage = cday - day;
} else {
mage = mage - 1
dage = 30 - (day - cday);
}
document.getElementById("output").innerHTML = "your age is " + dage + " days " + mage + " months " + yage + " years";
}
<html>
<head>
</head>
<body>
<p id="month">
</p>
<form id="form">
<!input type="text" id="day" placeholder="dd">
<! input type="text" id="day" placeholder="mm">
<!input type="text" id="day" placeholder="yyyy">
<input type="date" id="DOB">
<button id="inp">submit</button>
<br>
</form>
<p id="output"></p>
<script src="age.js"></script>
</body>
</html>
Your code contains earlier errors and could not reach the innerHTML yet.
Here's the error to start with:
Uncaught ReferenceError: cyear is not defined
You'll also have to add return false; to the end of the function to prevent the form from submitting, as stated by #thewatcheruatu.
date=new Date(); // Get current date
cyear=date.getFullYear(); // current year
cmonth=date.getMonth()+1; // current month
cday=date.getDate(); // current day
function getDOB()
{
var DOB=new Date(document.getElementById("DOB").value);
year=DOB.getFullYear();
month=DOB.getMonth();
day=DOB.getDate(); // getDate() function returns the current date
}
function execute()
{
getDOB();
yage=cyear-year;
if( cmonth>=month)
{
mage=cmonth-month;
}
else
{
mage=12-(month-cmonth);
yage=yage-1;
}
if ( cday>=day )
{
dage=cday-day;
}
else
{
mage=mage-1
dage=30-(day-cday);
}
document.getElementById("output").innerHTML="your age is "+dage+" days "+mage+" months "+yage+ " years";
}
<html>
<head>
</head>
<body>
<p id="month">
</p>
<form id="form">
<!input type="text" id="day" placeholder="dd">
<! input type="text" id="day" placeholder="mm">
<!input type="text" id="day" placeholder="yyyy">
<input type="date" id="DOB">
<button type="button" id="inp" onclick="execute()">submit</button><br>
</form>
<p id="output"></p>
<script src="age.js"></script>
</body>
</html>

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.

Categories