JavaScript function not working in Firefox and Safari (just in Chrome) - javascript

I have a page with already other JavaScripts correctly working... apart from this one:
<script>
function add(numDaysToAdd) {
var data_in = new Date (document.WADAInsertForm.data_in.value);
var data_out = data_in.setDate(data_in.getDate()+numDaysToAdd);
var final_day = data_out.getDate();
var final_month = data_out.getMonth() + 1;
var final_year = data_out.getFullYear();
document.WADAInsertForm.data_out.value = final_year+'-'+final_month+'-'+final_day;
}
</script>
This script is triggered by an OnChange call on a checkbox together with a OnClick event. To clarify:
<input type="checkbox" name="product" value="Insurance plan: 1 month" id="product" onClick="this.form.price.value='41.40'" onChange="add(+30)">
When I test the page in Chrome it does all the homeworks: insert the price value in the "price" field and update the "data_out" field with the proper value.
When I do the same in Firefox and Safari... it works only the "price" setting.
Any suggestions or help?

onChange="add(+30)"
Here +30 doesn't represent any String or any Integer in your script it would through a type error, to add days to the current date you could use this script
<script type="text/javascript" language="javascript">
function AddDays(toAdd) {
if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
var d = new Date();
d.setDate(d.getDate() + parseInt(toAdd));
document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
}
</script>
---------------------- UI ---------------
<div id="result">
</div>
<input type="text" value="0" onkeyup="AddDays(this.value);" />

onClick isn't valid. Use onclick.
And I find it strange to have both onclick and onchange on a checkbox. You should include your onclick in the onchange.

Related

Angular ngx-bootstrap is incorrectly writing to 2 different input boxes

I'm using this ngx-bootstrap datepicker for angular 5 - unless anyone can suggest a "better" one.
https://valor-software.com/ngx-bootstrap/#/datepicker
I'm having trouble with 2 input text boxes with an event click of a checkbox is is affecting Both inputs!
HTML template
input box #1
<input type="text"
class="form-control"
[(ngModel)]="HearingDate" name="HearingDate" id="HearingDate"
[minDate]="minDate"
[maxDate]="maxDate"
#dp="bsDatepicker"
bsDatepicker [(bsValue)]="bsValue"
[bsConfig]="dpConfig">
input box #2
<input type="text"
class="form-control"
[(ngModel)]="ReporterDate" name="ReporterDate" id="ReporterDate"
[minDate]="minDate"
[maxDate]="maxDate"
#xdp="bsDatepicker"
bsDatepicker [(bsValue)]="bsValue"
[bsConfig]="dpConfig">
ngModel binding
ReporterDate: any;
HearingDate: any;
Checkbox event function
onReporterChange(){
//this.reporter = !this.reporter;
var currentDt = new Date();
var mm = currentDt.getMonth() + 1;
var dd = currentDt.getDate();
var yyyy = currentDt.getFullYear();
var date = mm + '/' + dd + '/' + yyyy;
//BELOW IS SETTING NOT ONLY ReporterDate, but HearingDate too!
this.ReporterDate = date;
}
So the problem is this
function is SETTING NOT ONLY ReporterDate, but HearingDate too!
Perhaps it is all in the #dp or something that I don't quite understand ( template reference variables) ??

Validate form data before submit and based on the validation call another function using javascript

I am new to web development. I am building an application to log effort. Currently i am mandating the form elements. Need to check if all fields are populated and then export the form data to an excel.
I have written the below code, please do consider that i am a newbie into this before firing on me about the code ethics.
Currently i am not focusing on the CSS part, so i do not have a css file.
<html>
<head>
<script type="text/javascript" language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "E:\\sample.csv";
var file = fso.openTextFile(fileLoc, 8, true, 0);
file.writeline(passForm.inputText.value + ',' +
passForm.timeSpent.value + ',' +
passForm.SystemDate.value + ',' +
passForm.UserName.value);
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
onload = function systemDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = mm + '/' + dd + '/' + yyyy;
document.getElementById("date").value = today;
}
</script>
</head>
<body>
<p>Happily log your effort!</p>
<form>
Ticket Number : <input id="inc" type="text" name="inputText" required="true" size="20"><br> Effort(In Hours): <input id="tsp" type="text" name="timeSpent" required="true" size="20"><br> Date(Effor Put On) : <input id="date" type="text" name="SystemDate"
required="true"><br> Effort Logged By: <input type="text" name="UserName" value="Abrar" disabled="true"><br>
<input type="Submit" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
Please help me out in successfully validating all fields and exporting the data.
This is a much simpler code where i have marked field elements required but still the form data is getting exported even when the required fields are empty and in fact the validation is happening post export.
Try this - please note I have been pragmatic and used onload and form element access - that is because it will work in all browsers without loading things like jQuery etc. I have also not tested for valid date. There are thousands of scripts that do that
Also note that you need to remove the required if you want to do simple error handling yourself. If you want custom error handling taken care of by HTML5, you will face compatibility issues in IE <11
HTML5 form required attribute. Set custom validation message?
So this one uses simple validation now I removed required
<html>
<head>
<script>
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "E:\\sample.csv";
var file = fso.openTextFile(fileLoc, 8, true, 0);
file.writeline(passForm.inputText.value + ',' +
passForm.timeSpent.value + ',' +
passForm.SystemDate.value + ',' +
passForm.UserName.value);
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
function pad(num) {return String("0"+num).slice(-2)}
function systemDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
document.getElementById("date").value = pad(mm) + '/' + pad(dd) + '/' + yyyy;
}
window.onload=function() {
systemDate();
document.getElementById("myForm").onsubmit=function() {
if (this.inputText.value=="") {
alert("Please enter Ticket Number");
this.inputText.focus();
return false;
}
if (this.timeSpent.value=="") {
alert("Please enter TimeSpent");
this.timeSpent.focus();
return false;
}
WriteToFile(this);
return false; // cancel submit
}
}
</script>
</head>
<body>
<p>Happily log your effort!</p>
<form id="myForm">
Ticket Number : <input id="inc" type="text" name="inputText" size="20"><br> Effort(In Hours): <input id="tsp" type="text" name="timeSpent" size="20"><br> Date(Effor Put On) : <input id="date" type="text" name="SystemDate"
required="true"><br> Effort Logged By: <input type="text" name="UserName" value="Abrar" disabled="true"><br>
<input type="Submit" value="submit">
</form>
</body>
</html>

Combining Date and Time input strings as a Date object

I have two input tags for picking date and time from user.
<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>
These two values are passed to a function where I want to combine these two input values as a Date object:
new Date(y, m, d, hh, mm, a)
Which I can then use to plot an event's details in a Calendar. How can I combine these two values? I have tried:
start:new Date(sdate + stime)
start:new Date(sdate , stime)
start: new Date(sdate.getFullYear() + sdate.getMonth() + sdate.getDate() + stime.getHours + stime.getMinutes())
But none of what I have tried is working.
How do I achieve this when using AngularJS?
In angular it would go something like this:
Controller:
function exampleController($scope) {
$scope.title = "$Watch sample";
$scope.$watch('sdate', function() {
tryCombineDateTime();
});
$scope.$watch('stime', function() {
tryCombineDateTime();
});
function tryCombineDateTime() {
if($scope.sdate && $scope.stime) {
var dateParts = $scope.sdate.split('-');
var timeParts = $scope.stime.split(':');
if(dateParts && timeParts) {
dateParts[1] -= 1;
$scope.fullDate = new Date(Date.UTC.apply(undefined,dateParts.concat(timeParts))).toISOString();
}
}
}
}
HTML
<div ng-app ng-controller="exampleController">
<h2>{{title}}</h2>
<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>
{{fullDate}}
</div>
You need to make use of the $watch listener on a variable when it changes, then call your function.
Note: it would be even better if you make a directive for this.
Fidle
A very naive approach to combine these two is to split date-components and time-components and make a string. Then make a new Date object using this string.
Input is taken from here:
<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>
Then in script part, split date and time components as follows:
var dd = new Date(sdate).getDate();
var mm = new Date(sdate).getMonth()+1;
var yy = new Date(sdate).getFullYear();
var hh = new Date(stime).getHours();
var ms = new Date(stime).getMinutes();
Then Combine these components to form a string as required(in Calendar):
var x = yy + ',' + mm + ',' + dd + ' ' + hh + ':' + ms;
Now create a new Date object:
var finaldate = new Date(x);
You could do something like this, though this doesn't have anything to do with AngularJS and I can't test on older browsers. I am assuming that you are entering date/time as UTC and I am using Date to create an ISO8601 timestamp as an output. Also assumes that you are using a modern browser that supports HTML5 and ECMA5, otherwise you will need to modify the code.
HTML
<p>Start Date</p><p> <input id="myDate" ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input id="myTime" ng-model="stime" type="time" ></p>
<div id="myIso"></div>
Javasceipt
var myIso = document.getElementById('myIso'),
dateParts,
timeParts;
function joinPartsAsDate() {
if (dateParts && dateParts.length === 3 && timeParts && timeParts.length === 2) {
// dateParts[1] -= 1; could be done here
myIso.textContent = new Date(Date.UTC.apply(undefined, dateParts.concat(timeParts))).toISOString();
} else {
myIso.textContent = '';
}
}
document.getElementById('myDate').addEventListener('change', function (e) {
dateParts = e.target.value.split('-');
if (dateParts[1]) { // this could be done in joinPartsAsDate, here for clarity
dateParts[1] -= 1;
}
joinPartsAsDate();
}, false);
document.getElementById('myTime').addEventListener('change', function (e) {
timeParts = e.target.value.split(':');
joinPartsAsDate();
}, false);
On jsFiddle
After testing all stuff described here, i found a very simple solution.
In my view i have
<input type="date" ng-model="tsc.untilDate">
<input type="time" ng-model="tsc.untilTime">
In my Angular Controller both model elements are objects from type Date by default.
With input type="date" the time of this Date object is always 00:00.
With input type="time" the date part of the Date object ist allways set to today.
So i just read the daytime (if it is set) of the TimeDate Object and set it on the DateObject.
if(tsc.untilTime)
{
tsc.untilDate.setHours(tsc.untilTime.getHours());
tsc.untilDate.setMinutes(tsc.untilTime.getMinutes());
}
For those looking for a compact version install the momentjs library.
npm install moment --save
Add it to your file header.
import * as moment from 'moment';
Then just compose the dateTime object with the fluent interface.
let dateTime = moment(this.sdate)
.startOf('day')
.set('hour', this.sTime.getHours())
.set('minute', this.sTime.getMinutes() )
.toDate();
Try this
const timeAndDate = moment(this.sdate + ' ' + this.sTime.getHours() + ' ' + this.sTime.getMinutes());
console.log(timeAndDate.toDate());

Showing information in text fields with JavaScript

I have two text fields in a form and a submit button. When the user clicks on in it must show a box message, containing the information user has provided and the current time.
How can I do this? Keep in mind that I'm a beginner with JavaScript.
You mean something like this?
<form onsubmit="formMessage(this);">
<p>First Name: <input name="firstname" id="firstname" /></p>
<p>Last Name: <input name="lastname" id="lastname" /></p>
<p><input type="submit" name="submit" value="Submit!" /></p>
</form>
function formMessage(frm)
{
var fn = frm.firstname.value;
var ln = frm.lastname.value;
var dt = new Date();
alert("You entered " + fn + " " + ln + " at " + dt + "!");
}
Demo: http://jsfiddle.net/EBKJ5/
You could do something like the following ( if your elements have id's on them ):
document.getElementById( "buttonId" ).addEventListener( "click", function() {
alert( document.getElementById( "formId" ).value + " " + new Date() );
}, false );
You can include a javascript file in your solution/html file and add a function that employs document.getElementById('nameofyourtextbox').value to retrieve the value and then use an alert box to display the values provided and then add the date in.
This function can then be called on the onclick event of your button.
example:
function buttonClicked()
{
var d = new Date();
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
alert(document.getElementById('nameofyourtextbox') +", "+ document.getElementById ('nameofyour2ndtextbox') + ", "+ date +"/"+ month +"/"+ year);
}
Add the function to the onclick event of your button:
<...... onclick="buttonClicked();">
To add the .js file to your page:
<script type="text/javascript" src="nameofyourjsfile.js"></script>
The src attribute must be the path to where your .js file is stored.

Form value not populated by javascript in IE

I have a link which calls some javascript. The javascript populates a form value and submits it. Works fine in all browsers except internet explorer.
All other options on the page are links, thats why I also would like this option to be a link
thanks
<script type="text/javascript">
function timeZone(){
today = new Date()
difference = today.getTimezoneOffset()
var field = document.getElementById("form").timezone
alert("test")
if(difference < 0){
difference = difference * -1
field.value = "GMT+" + pad(Math.floor(difference/60), 2) + ":" + pad(difference%60, 2);
}
else{
field.value = "GMT-" + pad(Math.floor(difference/60), 2) + ":" + pad(difference%60, 2);
}
form = document.getElementById('form');
form.submit();
}
function pad(num, digits) {
num = String(num); while (num.length < digits) { num="0"+num; }; return num;
}
</script>
<form method="get" action="ViewLog.do?page=1" id="form">
<input id="timezone" name="timezone" type="hidden" value=""></input>
<img id="activityHistoryImage" Class = "navImage" src="imgs/history.png" alt="Activity history"/>
Activity history<br/>
<small class="navSubText">See your most recent activities </small>
</form>
Internet Explorer may or may not have issues with the fact that you've given an id of 'form' to your form element; I imagine it probably does. In general, it's best to avoid using tag names as the value on id or name attributes.
Also, your hidden input element has an id, yet you're not using it to reference it. Change:
var field = document.getElementById("form").timezone
to
var field = document.getElementById("timezone");
Declare variables with var.
Place ; where they should be.

Categories

Resources