Javascript Focus - javascript

I am using this script for i need a focus on every alert.i tried many ways but it is not working.
script:
function validateTime(obj) {
var timeValue = obj.value;
if(timeValue == "" || timeValue.indexOf(":") < 0) {
alert("Invalid Time format");
obj.value = "";
return false;
} else {
var sHours = timeValue.split(':')[0];
var sMinutes = timeValue.split(':')[1];
if(sHours == "" || isNaN(sHours) || parseInt(sHours) > 23) {
alert("Invalid Time format");
obj.value = "";
return false;
} else if(parseInt(sHours) == 0) sHours = "00";
else if(sHours < 10) sHours = "0" + sHours;
if(sMinutes == "" || isNaN(sMinutes) || parseInt(sMinutes) > 59) {
alert("Invalid Time format");
return false;
} else if(parseInt(sMinutes) == 0) sMinutes = "00";
else if(sMinutes < 10) sMinutes = "0" + sMinutes;
obj.value = sHours + ":" + sMinutes;
}
return true;
}
aspx:
<asp:TextBox ID="lblMonday" CssClass="lblMonday" runat="server" Width="55px" onchange="validateTime(this);"></asp:TextBox>

You just need to call obj.focus() after each alert. As in:
alert("Invalid Time format");
obj.value = "";
obj.focus();

You probably haven't called the focus() method on the text element. Also it is not a good practice to mix presentation and functionality. You must not use the onchange attribute in the HTML markup.
document.getElementById("lblMonday").onchange = function() {
if(!validateTime(this)) { this.focus(); }
}
You can remove much of the duplication by calling alert() and resetting the field's value in a single place, as in
document.getElementById("lblMonday").onchange = function() {
if(!validateTime(this)) {
this.focus();
this.value="";
alert("Invalid time format");
}
else {
//Do something else
}
}

Related

Disable required field when checkbox is selected to No

I am trying to disable option required when I select checkbox to "No"
So when I select "NO" and when I submit form I get a required message and It's return dropdown menu.
So in picture you can see better and you will understand the problem
When choice is selected to "NO"
https://i.imgur.com/kCFxTFA.jpg
When choice is selected to "YES"
https://i.imgur.com/cUPlZeb.jpg
When I selected choice NO and submit form I get required message
https://i.imgur.com/LvIxMM1.jpg
Source Code
Showing/Hidden content
$(document).ready(function () {
$("input[name$='Chapel']").click(function () {
var test = $(this).val();
if (test == 'No') {
$("div#hideChapel").hide();
}
else {
$("div#hideChapel").show();
}
});
});
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
Function for time and date validation
function dateValidation() {
if (document.getElementById('dateOfEvent').value == "")
document.getElementById("valDate").innerHTML = "<p>Date Field required.</p>";
else
document.getElementById("valDate").innerHTML = "";
}
function timeValidation() {
if (document.getElementById('TimeFrom').value == "")
{
document.getElementById("valTime").innerHTML = "<p>Time From Field required.</p>";
}
else
{
provjera();
document.getElementById("valTime").innerHTML = "";
}
}
Chapel Time validation
var isValidTIme = 1;
function chapelTime() {
var t = new Date();
var timeFrom = document.getElementById("TimeFrom").value;
var timeTo = document.getElementById("TimeTo").value;
var chapelTimeFrom = document.getElementById("ChapelTimeFrom").value;
var chapelTimeTo = document.getElementById("ChapelTimeTo").value;
d = t.getDate();
m = t.getMonth() + 1;
y = t.getFullYear();
//Convert time into date object
var d1 = new Date(m + "/" + d + "/" + y + " " + timeFrom);
var d2 = new Date(m + "/" + d + "/" + y + " " + timeTo);
var chd1 = new Date(m + "/" + d + "/" + y + " " + chapelTimeFrom);
var chd2 = new Date(m + "/" + d + "/" + y + " " + chapelTimeTo);
//Get timestamp
var t1 = d1.getTime();
var t2 = d2.getTime();
var cht1 = chd1.getTime();
var cht2 = chd2.getTime();
if (t2 < t1) {
var endDay = new Date(m + "/" + d + "/" + y + " " + "11:45 PM");
var startAnotherDay = new Date(m + "/" + d + "/" + y + " " + "12:00 AM");
if (cht1 > t2 && cht1 < t1) {
document.getElementById("valChapelTimeFrom").innerHTML = "<p>Chapel Time From must be between Event Time From and Event Time To values.</p>";
return false;
}
else if (cht1 < t1) {
document.getElementById("valChapelTimeFrom").innerHTML = "";
if (cht2 < cht1 || cht2 > t2) {
document.getElementById("valChapelTimeTo").innerHTML = "<p>Chapel Time To must be between Chapel Time From and Event Time To values.</p>";
return false;
}
else {
document.getElementById("valChapelTimeTo").innerHTML = "";
return true;
}
}
else if (cht2 < t1 && cht2 > t2) {
document.getElementById("valChapelTimeTo").innerHTML = "<p>Chapel Time To must be between Chapel Time From and Event Time To values.</p>";
return false;
}
else {
document.getElementById("valChapelTimeFrom").innerHTML = "";
document.getElementById("valChapelTimeTo").innerHTML = "";
return true;
}
}
else {
if (cht1 < t1 || cht1 > t2) {
document.getElementById("valChapelTimeFrom").innerHTML = "<p>Chapel Time From must be between Event Time From and Event Time To values.</p>";
return false;
}
else if (cht2 < t1 || cht2 > t2) {
document.getElementById("valChapelTimeFrom").innerHTML = "";
document.getElementById("valChapelTimeTo").innerHTML = "<p>Chapel Time To must be between Event Time From and Event Time To values.</p>";
return false;
}
else if (cht1 >= cht2) {
document.getElementById("valChapelTimeFrom").innerHTML = "";
document.getElementById("valChapelTimeTo").innerHTML = "";
document.getElementById("valChapelTimeTo").innerHTML = "<p>Chapel Time To must be greater then Chapel Time From.</p>";
return false;
}
else {
document.getElementById("valChapelTimeFrom").innerHTML = "";
document.getElementById("valChapelTimeTo").innerHTML = "";
return true;
}
}
}
There are rest of function for checking time and date
function provjera() {
if (chapelTime() == false || cocktailTime() == false || mainTime() == false) {
isValidTIme = 0;
}
else {
isValidTIme = 1;
}
}
function checkIfEmpty() {
if (document.getElementById("TimeFrom").value == "" || document.getElementById("TimeTo").value == "" || document.getElementById("ChapelTimeFrom").value == "" || document.getElementById("ChapelTimeTo").value == "" || document.getElementById("CocktailTimeFrom").value == "" || document.getElementById("CocktailTimeTo").value == "" || document.getElementById("MainTimeFrom").value == "" || document.getElementById("MainTimeTo").value == "") {
return false;
}
else {
provjera();
return true;
}
}
function provjeraBezChapela() {
if (cocktailTimeWithoutChapel() == false || mainTime() == false) {
isValidTIme = 0;
}
else {
isValidTIme = 1;
}
}
function checkIfEmptyWithoutChapel() {
if (document.getElementById("TimeFrom").value == "" || document.getElementById("TimeTo").value == "" || document.getElementById("CocktailTimeFrom").value == "" || document.getElementById("CocktailTimeTo").value == "" || document.getElementById("MainTimeFrom").value == "" || document.getElementById("MainTimeTo").value == "") {
return false;
}
else {
provjeraBezChapela();
return true;
}
}
I just only to disable required message when I choice "NO" and it should allow me to submit form.
Any suggestion ?
In your submit code you have to verify if the No option is selected, somethink like this:
if(document.getElementById('YesOption').checked) {
.........do something.......
}
if(document.getElementById('NoOption').checked) {
..... do other things without message....
}

Angular JS 24hr time Input Validation

I using HTML5 with AngularJS,i have an input field where i am allowing users to enter the time in 24 hour format eg:(13:00) . when the user clicks on submit button i need to validate whether the input is entered in the above format . If not i would like to throw an error message saying its invalid time . The problem is when i try to do it using normal javascript on ng-click its not working . please suggest me a good way of doing it . How should i do i angular way .
this is my javascript code
function validateTime(obj)
{
var timeValue = obj.value;
if(timeValue == "" || timeValue.indexOf(":")<0)
{
alert("Invalid Time format");
return false;
}
else
{
var sHours = timeValue.split(':')[0];
var sMinutes = timeValue.split(':')[1];
if(sHours == "" || isNaN(sHours) || parseInt(sHours)>23)
{
alert("Invalid Time format");
return false;
}
else if(parseInt(sHours) == 0)
sHours = "00";
else if (sHours <10)
sHours = "0"+sHours;
if(sMinutes == "" || isNaN(sMinutes) || parseInt(sMinutes)>59)
{
alert("Invalid Time format");
return false;
}
else if(parseInt(sMinutes) == 0)
sMinutes = "00";
else if (sMinutes <10)
sMinutes = "0"+sMinutes;
obj.value = sHours + ":" + sMinutes;
}
return true;
}

Javascript getting the Leap Year

I need help with my code. I need to call my function leapYear() to my FieldValidator() function to determine if the year given by the user is leap year or not.
Here is my code:
function FieldValidator() {
var err = "";
var valid = false;
var leap = new leapYear(year)
//year
if(document.getElementById('year').value == ""){
valid = true;
err += "Enter year \n";
document.getElementById('year').style.borderColor = "red";
}
else if(document.getElementById('year').value < 1000 || document.getElementById('year').value > 9999){
valid = true;
err += "Invalid Year \n";
document.getElementById('year').style.borderColor = "red";
}
else {
document.getElementById('year').style.borderColor = "green";
}
//month
if(document.getElementById('month').value == ""){
valid = true;
err += "Enter Month \n";
document.getElementById('month').style.borderColor = "red";
}
else if(document.getElementById('month').value < 1 || document.getElementById('month').value > 12){
valid = true;
err += "Invalid Month\n";
document.getElementById('month').style.borderColor = "red";
}
else {
document.getElementById('month').style.borderColor = "green";
}
//day
if(document.getElementById('day').value == ""){
valid = true;
err += "Enter day \n";
document.getElementById('day').style.borderColor = "red";
}
else if (document.getElementById('month').value == 2) {
if(document.getElementById('year').value == leap()) {
if(document.getElementById('day').value > 29) {
valid = true;
err += "invalid leap\n";
document.getElementById('day').style.borderColor = "red";
}
else {
document.getElementById('day').style.borderColor = "green";
}
}
else if(document.getElementById('year').value != leap()) {
if(document.getElementById('day').value > 28) {
valid = true;
err += "invalid \n";
document.getElementById('day').style.borderColor = "red";
}
else {
document.getElementById('day').style.borderColor = "green";
}
}
}
else if (document.getElementById('month').value != 2) {
if(document.getElementById('day').value < 1 || document.getElementById('day').value > 31 ) {
valid = true;
err += "Invalid day \n";
document.getElementById('day').style.borderColor = "red";
}
else {
document.getElementById('day').style.borderColor = "green";
}
}
else {
document.getElementById('day').style.borderColor = "green";
}
if(valid){
alert(err)
return false;
}
return true;
}
function leapYear(year)
{
return ((document.getElementById('year').value % 4 == 0) && (document.getElementById('year').value % 100 != 0)) || (document.getElementById('year').value % 400 == 0);
}
For anything time related, I'm using momentjs (either like you in the browser or on the server in nodejs).
It's as simple as this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js">
var year = 2015;
moment([year]).isLeapYear(); // false
</script>
The isLeapYear function itself is quit simple, too. So you can use that to determine if the year is a leap year or not.
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
Source

How to stop button text change after page load?

I have a two text box and Enable button.If the data is entered wrongly in the text box on clicking enable button it alerts it.If all the data is correct, on clicking the enable button,text must become disable .The problem is once i click enable it becomes disable for a second then the page loads it again goes to Enable.Can any one tell me what i am doing wrongly .Please provide a example if possible .Thanks in advance
Script to validate and change the button text
function validate
{
var cal1 = document.getElementById('<%=txtEndDate.ClientId%>').value;
var cal2 = document.getElementById('<%=txtStartDate.ClientId%>').value;
var button=document.getElementById('<%=button1.ClientId %>')
if (cal1 == '' && cal2 == '') {
alert("Start Date and End Date can not be left blank ");
return false;
}
if (cal1 == '') {
alert("End Date can not be left blank ");
return false;
}
if (cal2 == '') {
alert("Start Date can not be left blank ");
return false;
}
if (cal1 != '' || cal2 != '')
{
var dt1 = Date.parse(cal1);
var dt2 = Date.parse(cal2);
if (dt1 <= dt2) {
alert("End Date must occur after the Start date ");
return false;
}
}
//if the all the validation are correct it comes to this
if (button.value == "Enable")
button.value = "Disable";
else
button.value = "Enable";
return true;
}
button
<asp:Button ID="button1" OnClientClick=" return validate()" runat="server" Text="Enable" />
Condition will be && in place of || and you pass return false to stop postback
After completing your validation try to return false and use if - else will save your time of validate
function validate()
{
var cal1 = document.getElementById('<%=txtEndDate.ClientId%>').value;
var cal2 = document.getElementById('<%=txtStartDate.ClientId%>').value;
var button=document.getElementById('<%=button1.ClientId %>')
if (cal1 == '') {
alert("End Date can not be left blank ");
return false;
}
else if (cal2 == '') {
alert("Start Date can not be left blank ");
return false;
}
else if (cal1 != '' && cal2 != '')
{
var dt1 = Date.parse(cal1);
var dt2 = Date.parse(cal2);
if (dt1 <= dt2) {
alert("End Date must occur after the Start date ");
return false;
}
else{
//if the all the validation are correct it comes to this
if (button.value == "Enable")
button.value = "Disable";
else
button.value = "Enable";
}
}
return false;
}
and Button - <asp:Button ID="button1" OnClientClick=" return validate();" runat="server" Text="Enable" />
Your problem is that the default action of a click event of an button (<input type="button">) is to submit the form. You can prevent that by returning false from the event handler. the simplest way to do that in your case would be to ALWAYS return false from your validate function.
After completing your validation try to return false
function validate()
{
var cal1 = document.getElementById('<%=txtEndDate.ClientId%>').value;
var cal2 = document.getElementById('<%=txtStartDate.ClientId%>').value;
var button=document.getElementById('<%=button1.ClientId %>')
if (cal1 == '') {
alert("End Date can not be left blank ");
return false;
}
if (cal2 == '') {
alert("Start Date can not be left blank ");
return false;
}
if (cal1 != '' || cal2 != '')
{
var dt1 = Date.parse(cal1);
var dt2 = Date.parse(cal2);
if (dt1 <= dt2) {
alert("End Date must occur after the Start date ");
return false;
}
}
//if the all the validation are correct it comes to this
if (button.value == "Enable")
button.value = "Disable";
else
button.value = "Enable";
return false;
}

Date Validation not working using JavaScript

I have two two date fields - from date and to date, and i need to validate 3 things
Both the values are entered or not
Date datatype check
To date must be greater than from date.
But my script is not working.
can some body please check?
Thanks
function checkBothDates(sender,args)
{
var from = document.getElementById(sender.From);
var to = document.getElementById(sender.To);
var behaviorId = sender.behavior;
var from_value = from.value;
var to_value = to.value;
if((from_value == "")&&(to_value == ""))
{
args.IsValid = true;
}
else
{
if((from_value != "")&&(to_value != ""))
{
if((isValidDate(from_value))&&(isValidDate(to_value)))
{
if(from_value < to_value)
{
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please enter valid dates in both the fields";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
else
{
args.IsValid = false;
sender.errormessage = "Please make sure you enter both the values";
if(behaviorId != null)
{
openCollapsiblePanel(behaviorId);
}
}
}
}
function isValidDate(val)
{
var format = 'dd/MM/yyyy'
var regexp = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (!regexp.test(val))
{
return false;
}
else
{
try
{
$.datepicker.parseDate(format,val,null);
return true;
}
catch(Error)
{
return false;
}
}
}
Your code is pretty repetitive, you can shorten a lot of it.
Also note that the regex check is entirely unnecessary, since $.datepicker.parseDate() won't accept anything invalid anyway.
function checkBothDates(sender, args) {
var from = parseDate( $(sender.From).val() ),
to = parseDate( $(sender.To).val() );
args.IsValid = false;
if (from == "" && to == "" || from && to && from <= to) {
args.IsValid = true;
} else if (from == null || to == null) {
sender.errormessage = "Please enter valid dates in both the fields";
} else if (from > to) {
sender.errormessage = "To date must be greater than or equal to the from date";
} else {
sender.errormessage = "Please make sure you enter both the values";
}
if (!args.IsValid && sender.behavior) {
openCollapsiblePanel(sender.behavior);
}
}
function parseDate(val) {
if (val == "") return "";
try {
return $.datepicker.parseDate('dd/MM/yyyy', val);
} catch (ex) {
return null;
}
}
There is a problem in your code aroun the 19th line. You wrote:
if(from_value < to_value) {
args.IsValid = false;
sender.errormessage = "To date must be greater than or equal to the from date";
}
But you definitely want that from_value is smaller then to_value. Fix it!

Categories