using jquery set datepicker value to "" on form submission - javascript

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 =""

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>

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.

how to add one error instead of multiple errors

Hi I have designed my form now i am unsure how to combine all the alert messages instead of them popping up one at a time , please could someone tell my how to do this in simple terms as i am new to javascript. thankyou in advance. below is my script.
function validateForm() {
// this part of the script will collate all errors into one should the user leave an input blank
var Fname=document.forms["myForm"]["fname"].value;
var Lname=document.forms["myForm"]["lname"].value;
var address=document.forms["myForm"]["addr1"].value;
var postcode=document.forms["myForm"]["pcode"].value;
var email=document.forms["myForm"]["email"].value;
var number=document.forms["myForm"]["tel"].value;
var date=document.forms["myForm"]["mydate"].value;
if (Fname==null || Fname=="" ||Lname==null || Lname=="" ||address==null || address=="" ||!postcode||!email||!number||( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false )||(myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )||!date)
{
alert("Please make sure all fields are filled or checked correctly out ");
return false;
}
//end of collating script
//start of postcode script
var regPostcode = /^[a-zA-Z]{1,2}\d[\dA-Za-z]? \d[a-zA-Z]{2}$/;
if (!postcode.match(regPostcode))
{
alert("That Post Code is incorrect, correct way mk4 4tr");
return false;
}
//end of postcode script
//start of email script
var regEmail =/^\S+#\S+\.\S+$/;
if (!email.match(regEmail))
{
alert("That email is incorrect");
return false;
}
// end of email script
// start of phone number script
var phonestring = /^(?:0|\+44)[12378]\d{8,9}$/;
if (!number.match(phonestring))
{
alert(" incorrect,correct format 01908234874");
return false;
}
// end of phone script
//start of gender script
if ( ( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
// end of gender script
//start of age group script
if((myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )){
alert("please select an age group");
return false;
}
// end of age script
//start of datefield
var dateformat=/^(?:(?:31\/(?:0[13578]|1[02])|(?:29|30)\/(?:0[13-9]|1[012])|(?:0[1-9]|1\d|2[0-8])\/(?:0[1-9]|1[0-2]))\/[2-9]\d{3}|29\/02\/(?:[2-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[3579][26])00))$/;
if (!date.match(dateformat))
{
alert("format incorrect use dd/mm/yyyy make sure you are entering correct days to the month remember 30 days have september, april, june & november, only 28 days in february unless leap year next is 2016");
return false;
}
var today = new Date();
var courseYear =date.substr(6,4) // use substr or substring to capture the last four digits
var courseMonth =date.substr(3,2) // use substr or substring to capture the four and fifth digits
var courseDay = date.substr(0,2)//e the first and second digits
var dateToCompare = new Date(courseYear, courseMonth, courseDay);
if (dateToCompare < today) {
alert("this date is in the past");
return false; }
//end of date field
else
{ alert(" Thank you a member of our team will get back to you shortly");
return true;}
}
create some kind of collection that you can append to and instead of alerting independantly, just add them to the set. Something like:
function validateForm(){
var errors = []; // new array to hold all the errors
/*
validation code that instead of
alert('error')
use
errors.push('error');
Also remove any premature `return` statements and
leave them until the end.
*/
// next check if there are errors
if (errors.length > 0){
// display them
alert('Following errors found:\n- ' + errors.join('\n- '));
// also return false to flag there was a problem
return false;
}
// if we reached this code there were no errors
return true;
}
Add all your errors to an array and then alert them at the end, if any exist:
function validateForm() {
var errors = []; //array for holding errors
.
.
.
if (Fname==null || Fname=="" ||Lname==null || Lname=="" ||address==null || address=="" ||!postcode||!email||!number||( myForm.sex[0].checked == false ) && ( myForm.sex[1].checked == false )||(myForm.age[0].checked == false )&&(myForm.age[1].checked == false )&&(myForm.age[2].checked == false )&&(myForm.age[3].checked == false )&&(myForm.age[4].checked == false )||!date) {
errors.push("Please make sure all fields are filled or checked correctly out "); //add error
}
//end of collating script
//start of postcode script
var regPostcode = /^[a-zA-Z]{1,2}\d[\dA-Za-z]? \d[a-zA-Z]{2}$/;
if (!postcode.match(regPostcode)) {
errors.push("That Post Code is incorrect, correct way mk4 4tr"); //add error
}
//end of postcode script
//start of email script
var regEmail =/^\S+#\S+\.\S+$/;
if (!email.match(regEmail)) {
errors.push("That email is incorrect"); //add error
}
if(errors.length > 0) {
alert('The following errors occurred: ' + errors.join('\n')); //alert errors if they exist
return false;
}
return true; // allow submit
}

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.

Calling a function from another location on a button click event

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"

Categories