Calling a function from another location on a button click event - javascript

I need to call a function by clicking a button. The button is on an aspx page and the function is on a .js page.
This is the code I use for my button:
<asp:LinkButton ID="lnkBTNSubmit" runat="server" CssClass="buttonlink"
OnClick="lnkBTNSubmit_Click" OnClientClick="onBtnSubmitClick();">Submit</asp:LinkButton>
and this is my function:
function onBtnSubmitClick() {
var startDate = document.getElementById('<%= txtATrendStartDate.ClientID %>').value;
var endDate = document.getElementById('<%= txtATrendEndDate.ClientID %>').value;
checkDateRange(startDate, endDate);
}
function checkDateRange(start, end) {
// Parse the entries
var startDate = Date.parse(start);
var endDate = Date.parse(end);
// Make sure they are valid
if (isNaN(startDate)) {
alert("The start date provided is not valid, please enter a valid date.");
return false;
}
if (isNaN(endDate)) {
alert("The end date provided is not valid, please enter a valid date.");
return false;
}
// Check the date range, 86400000 is the number of milliseconds in one day
var difference = (endDate - startDate) / (86400000 * 7);
if (difference < 0) {
alert("The start date must come before the end date.");
return false;
}
return true;
}
Please note that the function is on an another .js page.

To call the function in the other js file you have to include a reference to the js file on your page.
Example:
Put this in your head tag:
"script src="SomeOtherJSFIle.js" type="text/javascript"/script"

Related

datetimepicker is not working correctly

I have created one custom control for datetime picker in one control i have given three mode datetimepicker,timepicker and datepicker.For which i have created one property called CalenderMode of type enum which stores these three modes and which value i am given to the property according to that i am changing the datetimepicker,if i given timepicker then my timepicker is enabled,if i give datepicker then date picker is enabled and if i give datetimepicker then my datetimepicker is enabled this i am handling in jquery.
For validation of these i am given format from c# and that format i am using in client side but now problem is if my timepicker or date picker is enabled and from timepicker i am selecting time but in text box it showing date time this is same for the date picker also there also it is showing date time.
Here i am not understanding what is the issue.
My code of jquery where i am changing the mode of calender using assigning the value to property is
$(document).ready(function () {
$('.calendercssclass').each(function () {
var result;
var value = $(this).closest('.DateControl').find("input[type=hidden][id*='CalenderTypeModeID']").val();
if (value == "timepicker") {
$(this).datetimepicker({
timepicker: true,
datepicker: false
//mask: true
});
}
else if (value == "datepicker") {
$(this).datetimepicker({
timepicker: false,
datepicker: true
// mask: true
});
}
else {
$(this).datetimepicker({
//mask: true
});
}
});
});
To give the format for validation i am using following code
function ValidateFormatOfDatecontrol(sender, args) {
debugger;
args.IsValid = true;
var format;
$('.calendercssclass').each(function () {
var result;
var value = $(this).closest('.DateControl').find("input[type=hidden][id*='CalenderTypeModeID']").val();
if (value == "timepicker") {
format = $(this).closest('.DateControl').find("input[type=hidden][id*='ClientTimeFormatID']").val();
var answer = $(this).val();
if (answer != '') {
//Moment.js inbuilt function for validating the date format .
args.IsValid = moment(answer, format, true).isValid();
}
}
else if (value == "datepicker") {
format = $(this).closest('.DateControl').find("input[type=hidden][id*='ClientDateFormatID']").val();
var answer = $(this).val();
if (answer != '') {
//Moment.js inbuilt function for validating the date format .
args.IsValid = moment(answer, format, true).isValid();
}
}
else if (value == "datetimepicker") {
format = $(this).closest('.DateControl').find("input[type=hidden][id*='ClientDateTimeFormatID']").val();
var answer = $(this).val();
if (answer != '') {
//Moment.js inbuilt function for validating the date format .
args.IsValid = moment(answer, format, true).isValid();
}
}
});
}
server side code for giving format for validation is
this.clientDateFormat.Value = "MM/DD/YYYY";
this.clientDateTimeFormat.Value = "mm/dd/yyyy H:i A";
this.clientTimeFormat.Value = "H:i";
Screenshot for issue is
Can anybody help me for this?
Here You are using Rain Jquery so fromat of Rain for the time is different from the moment what you are using for the validation so following is the format for both
Rain Jquery Time Format : h:i A
Moment Time Format : h:mm A
Following is the sample code
Script
$(document).ready(function () {
$(".date").datetimepicker({
format: 'h:i A',
datepicker:false
});
$(".date").change(function () {
var format = "h:mm A";
$('#message').text(moment($(".date").val(), format, true).isValid());
});
});
Markup
<div>
<asp:TextBox ID="TextBox1" runat="server" CssClass="date"></asp:TextBox>
<asp:Label ID="message" runat="server" CssClass="message"></asp:Label>
</div>

Javascript form validation, check if date is passed

I'm trying to validate a form here and I'm almost done. The only issue is I can't figure out a way of validating the dates field to check whether the date that has been put in hasn't passed. It has to be done through Javascript... btw, here is the HTML:
<label for="reservationDate">Date of reservation (DD/MM/YYYY):</label>
<input type="text" id="date" name="date" onblur="validateDate(date)">
<span id="dateError" style="display: none;">Please enter your date of reservation in this format DD/MM/YYYY</span>
Here is the Javascript:
function validateDate(x) {
var re = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/;
if(re.test(document.getElementById(x).value)){
document.getElementById(x).style.background ='#ccffcc';
document.getElementById(x + 'Error').style.display = "none";
return true;
} else{
document.getElementById(x).style.background ='#e35152';
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
Hope someone can help :)
Here's some code to make this a specific answer to suit your needs:
function validateDate(x) {
var re = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/;
var entered = new Date(document.getElementById(x).value);
var today = new Date();
if( entered > today ) {
document.getElementById(x).style.background ='#ccffcc';
document.getElementById(x + 'Error').style.display = "none";
return true;
} else{
document.getElementById(x).style.background ='#e35152';
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
Here is the working, tested code: http://jsfiddle.net/digitalextremist/rwhhg/1/
Some past answers which are pieces but not really the whole deal:
Check if date is in the past Javascript
Validate that end date is greater than start date with jQuery
Javascript to validate date entered

How to pass datepicker change event

I'm checking a date entered with a datepicker control in jquery from an Html.TextBoxFor helper:
<%=Html.TextBoxFor(c => Model.mydate, new { #class = "datepicker", maxlength = 10, #onBlur = "chkDate"})%>
The datepicker mask for the textbox appears to be MM/DD/YYYY . So, my script checks for an underscore and displays an error. This works if the user igonores the datepicker and tries to enter a date freehand but not if the datepicker is used. When a date is chosen, the value passed to my script is still underscores and no value. Here's my script:
<script type="text/javascript">
$(document).on("blur", "input[name=mydate]",
function chkDate() {
var len = $("input[name=mydate]").val().length;
var date = $("input[name=mydate]").val();
var month = date.slice(0, 2);
var day = date.slice(3, 5);
var year = date.slice(6, 10);
alert("chkBirthday " + month);
if (month == '__') {
document.getElementById("MainContent_ErrorMessage").visibility = 'visible';
document.getElementById("MainContent_ErrorMessage").innerHTML = 'No date has been entered. Please enter a date';
}
});
There's an event onChange associated with datepicker. Is this what I should be using? If so, how do I specify that in my helper and what script changes do I need to make?
Try this,
$(document).on("change", "input[name=mydate]",function (){
var len = $(this).val().length;
var date = $(this).val();
var month = date.slice(0, 2);
var day = date.slice(3, 5);
var year = date.slice(6, 10);
alert("chkBirthday " + month);
if (month == '__') {
document.getElementById("MainContent_ErrorMessage").visibility = 'visible';
document.getElementById("MainContent_ErrorMessage").innerHTML = 'No date has been entered. Please enter a date';
}
});
Assuming you are using the popular JQuery UI's Datepicker, weirdly enough they are not entitled events but callbacks that can handle this event. See onSelect or onClose.

using jquery set datepicker value to "" on form submission

I have a jsp code which on submit calls this function
function filterExcessPage() {
setDefaultValues();
var fromLast =document.getElementById('fromLast').value;
var fromDate =document.getElementById('fromDate').value;
var toDate =document.getElementById('toDate').value;
$("#excessListForm").submit(function() {
if((toDate.length>0) && (fromDate.length==0)) {
$('#validateDate').text('*from date is mandatory');
return false;
}else if ((fromDate.length>0) && (new Date(fromDate)>new Date())) {
$('#validateDate').text('*from date should be less than current date');
excessListForm.fromDate.value="";
return false;
}else if ((toDate.length>0) && (new Date(toDate)>new Date())) {
$('#validateDate').text('*to Date should be less than current date');
excessListForm.toDate.value="";
return false;
}else {
var queryUrl = "/excessManagement.web/inbox.htm?excessFilteredData=true&fromLast=" + fromLast+"&fromDate="+fromDate+"&toDate="+toDate;
excessListForm.action = queryUrl;
excessListForm.submit();
}
});
}
function setDefaultValues() {
excessListForm.cif.value="";
excessListForm.customerName.value="";
excessListForm.fromLast.value="";
excessListForm.fromDate.value="";
excessListForm.toDate.value="";
}
The fromdate and todate values reappear on form submission....
After form submission the values displayed in fromdate,todate textboxes are in the format i am using in my java class ....
I need to set the values to "" after form submission...
set in client side
var fromDate =document.getElementById('fromDate').value;
var toDate =document.getElementById('toDate').value;
fromDate.value= "";
toDate.value =""

Stopping the registarion on invalid input:JavaScript

I have a registration form with date of birth as one of the fields, I have written a function for future date which has to be invalid. But when the user puts a future date it still submits the form, although alert is being made to the user.
This is the function for alert, and its working fine.
var user_birth_year=document.getElementById("birth_year").value;
var user_birth_month=document.getElementById("birth_month").value;
var user_birth_day=document.getElementById("birth_day").value;
var userDate = new Date(user_birth_year,user_birth_month-1,user_birth_day);
var currentDate = new Date();
var res="Invalid date";
if(currentDate.getTime() < userDate.getTime() ) {
document.getElementById('registererror').innerHTML = "<span class='errorMsg'>"+res+"</span>";
document.getElementById('registererror').style.display = 'block';
} else {
document.getElementById('registererror').style.display = 'none';
}
Usually to stop the submit of a form, you need to return false on the form submit event.

Categories