How could I accomplish this with Jquery? - javascript

How can I make it so Jquery checks that ESNStart and ESNEND in the HTML form are in the same range otherwise it throws an alert saying that both numbers need to be in the same range to the user after typing in the value for ESNEnd ??
I still don't understand how I could also make it so ESNList gets checked for all its multiple values entered in the text field to be in the same range otherwise it also throws an alert to the user to enter a number in the same range as shown by the if statements ? A fiddle demonstrating this would help me learn so much , thanks a bunch !
<html>
<head>
<script type="text/javascript" src="jquery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function() {
$(":text").css("border", "2px solid red");
$(":text").keyup(function() {
var enteredData = $(this).val()
console.log(enteredData);
if (enteredData == "") {
$(this).css("border", "2px solid red");
} else {
$(this).css("border", "inherit");
}
if ($(this).attr("id") == "ESNList") {
esnList = parseInt(enteredData);
switch (true) {
case (esnList >= 986329 && esnList <= 999999):
$("#ddl_StxName").val("stx2");
$("#ddl_rtumodel").val("globalstar");
break;
case (esnList >= 660000 && esnList <= 699999):
$("#ddl_StxName").val("mmt");
$("#ddl_rtumodel").val("globalstar");
break;
case (esnList >= 200000 && esnList <= 299999):
$("#ddl_StxName").val("stm3");
$("#ddl_rtumodel").val("stmcomtech");
break;
case (esnList >= 1202114 && esnList <= 1299999):
$("#ddl_StxName").val("smartone");
$("#ddl_rtumodel").val("globalstar");
break;
}
}
});
});
</script>
</head>
<body>
<form id="provision">ESNList:
<input type="text" id="ESNList" name="ESNList" size="30" />
<br />ESN Start:
<input type="text" id="ESNStart" name="ESNStart" size="10" />
<br />ESN End:
<input type="text" id="ESNStart" name="ESNStart" size="10" />
<br />UnitName:
<input type="text" id="STxName" name="STxName" size="30" />
<br />Unit Model:
<select name="STxName" id="ddl_StxName">
<option value="stx2">STX2</option>
<option value="stm3" selected>STM3</option>
<option value="acutec">Acutec</option>
<option value="trackpack">Trackpack</option>
<option value="mmt">MMT</option>
<option value="smartone">Smartone</option>
<option value="smartoneb">SmartOneB</option>
</select>
<br />RTU Model Type:
<select name="rtumodel" id="ddl_rtumodel">
<option value="globalstar">GlobalStar</option>
<option value="both">Both</option>
<option value="comtech">Comtech</option>
<option value="stmcomtech">STMComtech</option>
</select>
<br />
<input type="submit" value="submit" />
</form>
</body>
</html>

I created some methods that seem to work, although I haven't created groups of numbers that are out of range.
I strongly suggest you don't allow user to enter comma separated lists as it will be hard to point to user the invalid entries. It would be a lot cleaner having each number in it's own input. You can easily add a button for "Add new number" and create a new input for it.
I used arrays to store ranges and the values for the valid range that get changed for other fields. This module is not trivial and suggest you create a testing sandbox with a wide variety of numbers you can test with.
$('#ESNList').keyup(function(){
var enteredData = $(this).val();
$(this).removeClass('valid');
if( enteredData == ''){
return;
}
if(hasMultipleValues(enteredData)){
var range=rangeCheckMultipleNumbers(enteredData)
if( range===false){
log('Numbers not in same range');
return;
} else{
setRangeValues(range);
$(this).addClass('valid');
}
}
var rangeIdx = getRangeIndex(enteredData);
if(rangeIdx===false){
log('Number not in range');
}else{
setRangeValues(rangeIdx);
$(this).addClass('valid');
}
});
function hasMultipleValues( str){
/* second test for a singel entry with comma at end*/
return str.indexOf(',') !=-1 && str.indexOf(',') != str.length-1;
}
var ranges = [
[986329, 999999],
[660000, 699999],
[200000, 299999],
[1202114, 1299999]
];
var rangeText = [
["stx2", "globalstar"],
["mmt", "globalstar"],
["stm3", "stmcomtech"],
["smartone", "globalstar"]
]
/* returns range index if all in same range, otherwise returns false*/
function rangeCheckMultipleNumbers(str) {
var nums = str.split(',');
var rangeMatch = true; /* clean array to remove empty values if extra commas*/
nums = $.grep(array, function(item, index) {
return parseInt(item);
});
var groupRange = getRangeIndex(nums[0]);
if(nums.length > 1) {
for(i = 1; i < nums.length; i++) {
if(!checkSameRange(nums[i - 1], nums[i])) {
rangeMatch = false;
}
}
}
return rangeMatch ? groupRange : false;
}
function setRangeValues(rangeIndex) {
$("#ddl_StxName").val(rangeText[rangeIndex][0]);
$("#ddl_rtumodel").val(rangeText[rangeIndex][1]);
}
function checkSameRange(num1, num2) {
return getRangeIndex(parseInt(num1, 10)) == getRangeIndex(parseInt(num2, 10));
}
/* returns false if out of range, otherwise returns range index*/
function getRangeIndex(num) {
var idx = false;
$.each(ranges, function(i, range) {
if(num >= range[0] && num <= range[1]) {
idx = i;
return false;
}
});
return idx;
}
DEMO: http://jsfiddle.net/hXsQ8/1/

Related

How to allow one specific word into text field in form using javascript?

I have input number field which is from 1000 to 10000 range but I also want to allow one only word 'All' into this field if user enter any word then show error. I have not written any JavaScript code for this because I do not have any idea how to do this. can anyone help me out please? Thanks
<input type="text" class="form-control" id="validationCustom02" min="1000" max="10000" required>
Here is my javascript solution: It uses a single If statement to check if the string is a number or ALL. Technically you don't need the isNaN function in there so if you want to remove it, the if statement will still work.
var _input = document.querySelector(".validate-num");
var _min= 1000;
var _max = 10000;
_input.addEventListener("input",function(){
var _valid = ((isNaN(this.value) && this.value.toLowerCase() == "all") || (!isNaN(this.value) && (this.value >= _min && this.value <= _max)));
if(!_valid){
var error = document.getElementById("error");
error.innerHTML = "Value Must be 1000 to 10000 or ALL";
}
});
<input type="text" class="validate-num form-control" id="validationCustom02" required>
A number type can't have strings into it, you will have to have a text input with an Event listener which does the validation job For You. Here, I have added a blur listener, it would trigger once you move away from the input.
const inputElem = document.querySelector('#validationCustom02required');
inputElem.addEventListener('blur', (e) => {
const val = e.target.value;
let showError = false;
if (isNaN(val)) {
if (val.toLowerCase() !== 'all') {
showError = true;
}
} else {
const numVal = +val;
if (val < 1000 || val > 10000) {
showError = true;
}
}
const errorElem = document.querySelector('#error');
if (showError) {
errorElem.innerText = 'Invalid; Value!';
} else {
errorElem.innerText = '';
}
})
<input type="text" class="form-control" id="validationCustom02required">
<div id="error"></div>

Some of the JavaScript code doesn't work

I have a HTML select which onchange fires a function run()
<select id="select-para" onchange="run();">
<option value="paragraph 1...">Para 1</option>
<option value="paragraph 2...">Para 2</option>
<option value="paragraph 3...">Para 3</option>
<option value="paragraph 4....">Para 4</option>
</select>
What run() does is that it set value of select equals a variable text and value of text is set equal to value of input box.
function run(){
var text = document.getElementById("select-para").value;
var storyTextarea = document.getElementById("storytext");
storyTextarea.value = text;
}
I am making a typing test and I want user to select paragraph of his choice. Problem is that after this function ends, the rest of typing test code doesn't fire. Paragraph in input box changes but rest of typing test code doesn't work. How to make rest of code work? Rest of code is here.
var textArr = text.split(" ");
var usertext = "";
var lastWord = ""
var usertextArr = new Array();
var mistakes = new Array();
var highlightArgs = new Array();
var score = 0;
var count = 0;
var highlightIndex = 0;
//Prevent pasting into user text box
$('textarea').bind("cut paste", function (e) {
e.preventDefault();
});
//Keep highlighted text responsive
$(window).on('resize', function(){
$(".highlightTextarea").css('width','100%');
$(".highlightTextarea-container").css('width','99%');
if (highlightArgs.length > 0){
updateHighlight();
}
});
//Jump to next word to be typed
function textJump(jumpIndex){
var textStr = text.substring(0, jumpIndex);
storyTextarea.value = textStr;
storyTextarea.scrollTop = storyTextarea.scrollHeight;
storyTextarea.value = text;
}
//Jump to specified line of TextArea
//OLD METHOD DO NOT USE
function textareaJump(line){
storyTextarea = document.getElementById("storytext");
var lht = (storyTextarea.clientHeight / storyTextarea.rows)*0.875;
var jump = (line - 1) * lht;
storyTextarea.scrollTop = jump;
}
//Refresh the highlighted area
function updateHighlight(){
$('#storytext').highlightTextarea('destroy');
$('#storytext').highlightTextarea({ ranges: highlightArgs });
}
function typeTest(){
function updateUsertext(){
usertext = $('textarea#usertext').val();
var usertextLatestArr = usertext.split(" ");
usertextArr.push(usertextLatestArr[usertextLatestArr.length-1]);
count = usertextArr.length - 1;
var wordLen = textArr[count].length;
var charBufferIndex = textArr[count].length < 3 ? 5 : 2;
//Word spelling matches
if(textArr[count] === usertextArr[count]){
if (mistakes[mistakes.length-1] === count){ mistakes.pop() }
score++;
highlightArgs.push({ color: '#c1f5b0', start: highlightIndex, length: wordLen })
highlightIndex += (wordLen + 1);
}
//Missed one word
//any more than a single consecutive missed word counts as an error
else if(textArr[count+1] === usertextArr[count]){
usertextArr.splice(count, 0, "blank");
if (mistakes[mistakes.length-1] === count){ mistakes.pop() }
score++;
mistakes.push(count);
highlightArgs.push({ color: '#febbb9', start: highlightIndex, length: wordLen })
highlightIndex += (wordLen + 1);
highlightArgs.push({ color: '#c1f5b0', start: highlightIndex, length: textArr[count+1].length })
highlightIndex += (textArr[count+1].length + 1);
}
//Spelling mistake
else{
highlightArgs.push({ color: '#febbb9', start: highlightIndex, length: wordLen })
highlightIndex += (wordLen + 1);
mistakes.push(count);
}
//Rebuild the highlight object
updateHighlight();
//Jump to the next word
var jumpIndex = highlightIndex + (wordLen + 1) + charBufferIndex;
textJump(jumpIndex);
};
//User presses backspace
$('#usertext').on('keydown', function(e) {
var lastChar = $('textarea#usertext').val().slice(-1);
var secondLastChar = $('textarea#usertext').val().slice(-2).substring(0, 1);;
if(e.keyCode == 8 && lastChar === " " && secondLastChar !== " "){
usertextArr.pop();
mistakes.pop();
highlightArgs.pop();
updateHighlight();
highlightIndex -= ( textArr[count].length + 1 );
count--;
}
});
$('#usertext').on('keydown', function(e) {
var lastChar = $('textarea#usertext').val().slice(-1);
var spaceTest = lastChar === " " ? true : false;
if(e.keyCode == 32 && spaceTest == false){
updateUsertext();
}
});
}
How to make all code work and typing test function smoothly. Here is the HTML:
<select id="select-para" onchange="run();">
<option value="paragraph 1...">Para 1</option>
<option value="paragraph 2...">Para 2</option>
<option value="paragraph 3...">Para 3</option>
<option value="paragraph 4....">Para 4</option>
</select>
<div class="typebox">
<textarea id="storytext" name="storytext" class="form-control" type="text" readonly="readonly" rows="3"></textarea>
</div>
<div class="typebox">
<textarea id="usertext" name="usertext" type="text" class="form-control" rows="2" placeholder="Start typing here to begin the test..."></textarea>
</div>
<div class="timer">You have <span id="time" class="timerTime">02:00</span> minutes left.</div>
Add typeTest() while onChange of paragraph
<select id="select-para" onchange="run(); typeTest();">
include the
$("#usertext").bind("cut paste", function (e) {
e.preventDefault();
});
//Keep highlighted text responsive
$(window).on('resize', function(){
$(".highlightTextarea").css('width','100%');
$(".highlightTextarea-container").css('width','99%');
if (highlightArgs.length > 0){
updateHighlight();
}
});
in run() function, so that the handlers get registered.
remove "textarea" from, as it is not needed to identify the ID.
$("textarea#usertext")
The logic may need to be properly formatted to work properly for all the other keycodes apart from '8' bs and '32' space.

Form validation backwards compatible with earlier versions of IE

I know this is an on going concern in IT these days with different versions of IE being used between different machines, but I was wondering if someone might be able to advise me on how to successfully make this code (which works fine for all my form validation in IE 10, FireFox, Chrome, etc) work in earlier versions of IE.
The version I am testing it against is IE7.
function validate(form){
var p = form.getElementsByTagName("p");
var valid = true;
for(var i = 0; i < p.length; i++){
var inputs = p[i].getElementsByTagName("*");
if(p[i].className == "required" || p[i].className == "required error"){
for(var n = 0; n < inputs.length; n++){
switch(inputs[n].tagName){
case "INPUT":
if(inputs[n].value.trim() == "" || inputs[n].value == null){
if(+navigator.sayswho[1] < 9){
//JavaScript for IE version 8 and below
}
else{
inputs[n].className = inputs[n].className.replace( /(?:^|\s)error(?!\S)/ , "" );
inputs[n].className = inputs[n].className+" error";
p[i].className = "required error";
}
valid = false;
}
break;
case "SELECT":
if(inputs[n].options[inputs[n].selectedIndex].value == 0 || select.value == null){
if(+navigator.sayswho[1] < 9){
//JavaScript for IE version 8 and below
}
else{
inputs[n].className = inputs[n].className.replace( /(?:^|\s)error(?!\S)/ , "" );
inputs[n].className = inputs[n].className+" error";
p[i].className = "required error";
}
valid = false;
}
break;
}
}
}
}
if(valid){
var elements = form.getElementsByTagName("*");
for(var i = 0; i < elements.length; i++){
switch(elements[i].type){
case "submit":
elements[i].disabled = true;
break;
case "reset":
elements[i].disabled = true;
break;
case "button":
elements[i].disabled = true;
break;
}
}
return true;
}
return false;
}
+navigator.sayswho[1] is a value from another question I found on here that returns an int representing the browser's version (in this case 7)
An example of a form field is:
<p class="required">
<span>Required Field</span>
<input type="text" id="username" name="username" class="logon_field" onfocus="clearError(this)" placeholder="Username" autofocus />
</p>
The method is called using validate(this) in the form's onsubmit attribute
Thanks in advance!
Ah.. doing some looking here on SO. Seems there are some issues with getElementsByClassName and IE7.
getElementsByName in IE7
I'd solve it by breaking things into a couple of different pieces, shown below.
Free bonus, BTW. 'addClass' 'removeClass' and 'hasClass'
It is better to put the required attribute (or the class) on the input field itself, rather than on the wrapper... though you can set the wrapper's class to show the field is in error.
<doctype html>
<html>
<head>
<title>
Test page
</title>
<script>
function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
function clearError(element) {
}
function validate(form) {
var i, l;
var input;
// First, let's check the input fields
var inputs = form.getElementsByTagName("input");
for (i = 0; i < inputs.length; i++) {
input = inputs[i];
// Skip stuff we don't want.
// You'll want password this list yet.
if (input.type !== "text") {
continue;
}
if (input.required || hasClass(input, "required")) {
if (input.value == "") {
alert(input.name + " is required");
}
}
}
}
</script>
</head>
<body>
<form action="#" onsubmit="validate(this); return false">
<p>
<label for="username">Required Field</label>
<input type="text" class="required" id="username" name="username" class="logon_field" onfocus="clearError(this)" placeholder="Username" autofocus />
</p>
<p>
<label for="trivia">Trivia Question</trivia>
<input type="text" id="trivia" name="trivia" class="" onfocus="clearError(this)" placeholder="Username" autofocus />
</p>
<input type="submit">
</form>
</body>
</html

change value upon select

what i'm aiming is to show the other div when it selects one of the two options
Full time and Part Time
and if possible compute a different value for each
When the user selects Part time
the value of PrcA will change to PrcB
this is the code i used
<!====================================================================================>
<script language="javascript">
<!--//
function dm(amount)
{
string = "" + amount;
dec = string.length - string.indexOf('.');
if (string.indexOf('.') == -1)
return string + '.00';
if (dec == 1)
return string + '00';
if (dec == 2)
return string + '0';
if (dec > 3)
return string.substring(0,string.length-dec+3);
return string;
}
function calculate()
{
QtyA = 0;
TotA = 0;
PrcA = 1280;
PrcB = 640;
if (document.form1.qtyA.value > "")
{ QtyA = document.form1.qtyA.value };
document.form1.qtyA.value = eval(QtyA);
TotA = QtyA * PrcA;
document.form1.totalA.value = dm(eval(TotA));
Totamt =
eval(TotA) ;
document.form1.GrandTotal.value = dm(eval(Totamt));
}
//-->
</script>
<!====================================================================================>
<p>
<label for="acct" style="margin-right:90px;"><strong>Account Type<strong><font color=red size=3> * </font></strong></label>
<select name="acct" style="background-color:white;" class="validate[custom[serv]] select-input" id="acct" value="">
<option value="Full Time">Full-Time</option>
<option value="Part Time">Part-Time</option>
<option selected="selected" value=""></option>
</select></p>
<!====================================================================================>
<script>
$(document).ready(function() {
$("input[name$='acct']").select(function() {
var test = $(this).val();
$("div.desc").hide();
$("#acct" + test).show();
});
});
</script>
<!====================================================================================>
<p>
<table><tr><td>
<lable style="margin-right:91px;"># of Agent(s)<font color=red size=3> * </font></lable>
</td><td>
<input style="width:25px; margin-left:5px;" type="text" class="validate[custom[agnt]] text-input" name="qtyA" id="qtyA" onchange="calculate()" />
</td><td>
<div id="acctFull Time" class="desc">
x 1280 =
</div>
<div id="acctPart Time" class="desc" style="display:none">
x 640 =
</div>
</td><td>
$<input style="width:80px; margin-left:5px;" type="text" readonly="readonly" name="totalA" id="totalA" onchange="calculate()" />
</p>
</td></tr></table>
is there any way for me to achieve this?
Check this [FIDDLE] ..
Added two classes to the div's which show the amount.. This should make like easier to access them..
$(document).ready(function() {
$("#acct").on('change', function() {
var selVal = $(this).val();
if (selVal == '1') { // Full Time
$('.parttime').hide();
$('.fulltime').show();
$('.agent').show();
$('.error').hide();
}
else if (selVal == '2') { // Part Time
$('.parttime').show();
$('.fulltime').hide();
$('.agent').show();
$('.error').hide();
}
else {
$('.parttime').hide();
$('.fulltime').hide();
$('.agent').hide();
$('.error').show();
}
});
$('#qtyA').on('change', function() {
var selVal = $("#acct").val();
if (!isNaN($(this).val())) {
var total = 0;
if (selVal == '1') {
total = parseInt($(this).val()) * 1280;
}
else if (selVal == '2') {
total = parseInt($(this).val()) * 640;
}
$('#totalA').val(total.toFixed(2));
}
else {
$(this).val('0');
$('#totalA').val('0.00');
}
});
});​
Also you can completely eliminate the vanilla javascript and go with jQuery that should be lot easier..
got the answer this is what i used
<script type="text/javascript">
$(document).ready(function(){
$('#acct').change(function() {
$('.box').hide();
$('#acct' + $(this).val()).show();
});
});
</script>
A jsfiddle would help tremendously here. However, it sounds like you're trying to:
Show/hide content containers based on a pulldown selection, and
Process a field value based on the pulldown selection.
These two problems could generally be addressed like so (assuming jQuery, per your snippit):
<select id="time-select">
<option value="full">Full-Time</option>
<option value="part">Part-Time</option>
</select>
<div id="full-detail" class="detail">
Full-time info.
</div>
<div id="part-detail" class="detail">
Part-time info.
</div>
<input type="text" id="computed-value"/>
<script>
$(function() {
"use strict";
function computeValueBasedOn( opt ) {
// Evaluate the computed value here...
return opt ? "do" : "stuff";
}
$("#time-select").change(function(evt) {
$(".detail").hide();
$("#"+ this.value +"-detail").show();
$("#computed-value").val( computeValueBasedOn( this.value ) );
});
});
</script>

date validation in javascript using .js files

I am having a ini.jsp page for creating a form for adding two text fields to input date and then using javascript in the ini.jsp page itself to validate those dates. I now have some library files(calendar.js, calendar-en.js, calendar-setup.js, calendar_1.png, calendar_system.css).
Now my question is how to I link these files to javascript (I am using ECLIPSE IDE) so that it displays calendar beside the textboxes for date in the format dd/mm/yyyy. . .
I have gone through lots of stuff, tried doing those but really couldn't get the expected output.
Below is the code that i have implemented so far
<html lang="en">
<head>
<style type="text/css" src="../datePickers/calendar-system.css">
</style>
</head>
<body>
<script language="Javascript" src="../Scripts/calendar.js"></script>
<h1>Report Generation</h1>
<div style="margin: 0 auto; width: 100%; text-align: left">
<form name="date" action="<c:url value="cli.htm"/>"
method="post" onSubmit="return ValidateForm()">
<fieldset>
<legend>Please enter Start Date and End Date</legend>
<div style="text-align: center; margin: 150px auto 100px auto;">
<label for="dateFrom">Start Date:</label>
<font color="#CC0000"><b>(dd/mm /yyyy)</b></font>
<input type="text" name="dateFrom" maxlength="25" size="25"
id="dateFrom" />
<img src = "../Images/calendar_1.png" onclick="javascript:Calendar.setup(inputField,ifFormat,button) style="cursor: pointer" />
</div>
<div style="text-align: center; margin: 150px auto 100px auto;">
<label for="dateTo">End Date:</label>
<font color="#CC0000"><b>(dd/mm/yyyy)</b></font>
<input type="text" name="dateTo" maxlength="25" size="25"
id="dateTo" />
</div>
<div>
<input type="submit" value="Generate Report" align="center" />
</div>
</form>
</div>
<script language="Javascript" >
var dtCh= "/";
var minYear=1900;
var maxYear=2500;
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Checking that the current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9")))
return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag){
var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
function daysInFebruary (year){
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31
if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
if (i==2) {this[i] = 29}
}
return this
}
function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(dtCh)
var pos2=dtStr.indexOf(dtCh,pos1+1)
var strDay=dtStr.substring(0,pos1)
var strMonth=dtStr.substring(pos1+1,pos2)
var strYear=dtStr.substring(pos2+1)
strYr = strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert("The date format should be : dd/mm/yyyy");
return false;
}
if (strMonth.length<1 || month<1 || month>12){
alert("Please enter a valid month");
return false;
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day");
return false;
}
if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
return false;
}
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))== false){
alert("Please enter a valid date");
return false;
}
return true;
}
function ValidateForm(){
var dt1=document.date.dateFrom
var dt2=document.date.dateTo
if (!isDate(dt1.value)){
dt1.value='';
dt1.focus();
return false;
}
if(!isDate(dt2.value)){
dt2.value='';
dt2.focus();
return false;
}
return true
}
}
</script>
</body>
</html>
I want changes in code to be done as:
The code should initialises the calendar object and links an image to a text field (using their IDs) to respond to a click.
Calendar.setup(
{
inputField : "dateFrom", // ID of the input field
ifFormat : "%d/%m/%Y", // the date format
button : "imgCal" // ID of the calendar image
}
);
should I really need to create a calendar object if so, can I know where. Also, where should I place the Calendar.setup code in my jsp page?
Can someone please help me sort out this issue...
Quick suggestion: Have you tried looking into this page.
Easy to implement and you can see the demo as well.
http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/
**
Now, Looking into your code; can you please flick the calender.setup(foo1, foo2...) function implementation? (Is this your customized library?)
Thanks,
i am trying to validate date with **YYYY\MM\DD of format using HTML and Javascript
Hope its Help you...
try to yourself...
< script type = "text/javascript" >
function valdate() {
var regdate = /^(19[0-9][0-9]|20[0-9][0-9])\/(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])$/;
if (form1.txtdate.value.match(regdate)) {
return true;
} else {
alert("! please Enter the Date in this Format 'YYYY/MM/DD'");
form1.txtdate.value = "";
form1.txtdate.focus();
return false;
}
} < /script>
<from="form1" method="post" action="">
<input name="txtdate" type="text" onblur="valdate()" maxlength="10" required />
</form>
if helpful so make voting....

Categories

Resources