Text and Date Manipulation

S

sgershon

Hi.

I know this is should be a simple question.
I know server-side web-programming, and never needed to use client-side
scripting... until now :)

I have done so far a little number of scripts that work well. But there
are two that I am having special difficulties with:

1)
I have a SELECT type input, "document.form_name.select_input".
I have a TEXTAREA type input, "document.form_name.text_area".
I have a BUTTON "button".
When "button" is pressed, "text_area"s value should be
"text_area"+"select_input"s value.

2)
I have a TEXT type input "document.form_name.date1".
I have a TEXT type input "document.form_name.date2".
I have a TEXT type input "document.form_name.days".
When any of the first two changes (to a date in the format
"dd/mm/yyyy"), the third one should contain the difference between the
dates, in days.

Any help with these?

Thanks;
SGershon
 
M

McKirahan

Hi.

I know this is should be a simple question.
I know server-side web-programming, and never needed to use client-side
scripting... until now :)

I have done so far a little number of scripts that work well. But there
are two that I am having special difficulties with:

1)
I have a SELECT type input, "document.form_name.select_input".
I have a TEXTAREA type input, "document.form_name.text_area".
I have a BUTTON "button".
When "button" is pressed, "text_area"s value should be
"text_area"+"select_input"s value.

2)
I have a TEXT type input "document.form_name.date1".
I have a TEXT type input "document.form_name.date2".
I have a TEXT type input "document.form_name.days".
When any of the first two changes (to a date in the format
"dd/mm/yyyy"), the third one should contain the difference between the
dates, in days.

Any help with these?

Thanks;
SGershon

It sounds like a school assignment.
 
K

kaeli

I have done so far a little number of scripts that work well. But there
are two that I am having special difficulties with:

Neither are very hard.
Are you sure this isn't homework?
1)
I have a SELECT type input, "document.form_name.select_input".
I have a TEXTAREA type input, "document.form_name.text_area".
I have a BUTTON "button".
When "button" is pressed, "text_area"s value should be
"text_area"+"select_input"s value.

Hints:
-- onclick
-- document.form_name.select_input.options
[document.form_name.select_input.selectedIndex].value
-- document.form_name.text_area.value
-- NaN / isNaN
2)
I have a TEXT type input "document.form_name.date1".
I have a TEXT type input "document.form_name.date2".
I have a TEXT type input "document.form_name.days".
When any of the first two changes (to a date in the format
"dd/mm/yyyy"), the third one should contain the difference between the
dates, in days.

Hints:
-- onChange
-- http://www.w3schools.com/js/js_obj_date.asp

HTH

--
 
S

SGershon

:)
No, it is not a school homework. I can see that the question is written
as one, maybe cause I used to teach in a kinder-garden... :)

I am 26 years old, so if it was a school assignment, my teacher would
be real mad at me! lol!

I have done simple pages on HTML/PHP, and went very well without
JavaScript (I know its powerfull and has lots of capabilities). Now one
of the scripts I need to do has to change many things dynamically
before submitting it. Many of the functions I've already done and they
are working, but these two keep giving me errors or wrong results.

Thanks for the education concern, anyway!
And thanks for any help you can give me.
 
K

kaeli

Neither are very hard.
Are you sure this isn't homework?

Oh, if it IS homework and you want it completed, just sent me $30 (I take
Paypal).
I'll be happy to do your work for you. :p

--
 
M

Mick White

Hi.

I know this is should be a simple question.
I know server-side web-programming, and never needed to use client-side
scripting... until now :)

I have done so far a little number of scripts that work well. But there
are two that I am having special difficulties with:

1)
I have a SELECT type input, "document.form_name.select_input".
I have a TEXTAREA type input, "document.form_name.text_area".
I have a BUTTON "button".
When "button" is pressed, "text_area"s value should be
"text_area"+"select_input"s value.

2)
I have a TEXT type input "document.form_name.date1".
I have a TEXT type input "document.form_name.date2".
I have a TEXT type input "document.form_name.days".
When any of the first two changes (to a date in the format
"dd/mm/yyyy"), the third one should contain the difference between the
dates, in days.

Such an endeavour is fraught with danger; relying on a user to enter the
correct format, that is.

days.value= Math.floor ((new Date (date1.value)-new Date
(date2.value))/(1000*60*60*24));

Need some error checking, though.
Mick
 
M

McKirahan

SGershon said:
:)
No, it is not a school homework. I can see that the question is written
as one, maybe cause I used to teach in a kinder-garden... :)

I am 26 years old, so if it was a school assignment, my teacher would
be real mad at me! lol!

I have done simple pages on HTML/PHP, and went very well without
JavaScript (I know its powerfull and has lots of capabilities). Now one
of the scripts I need to do has to change many things dynamically
before submitting it. Many of the functions I've already done and they
are working, but these two keep giving me errors or wrong results.

Thanks for the education concern, anyway!
And thanks for any help you can give me.

Will this get you started? Watch for word-wrap.

This uses Mick White's formula for "days".

<html>
<head>
<title>SGershon.htm</title>
<script type="text/javascript">
function append(form) {
var what =
form.select_input.options[form.select_input.selectedIndex].value;
form.text_area.value += what;
}
function calc(form) {
var dat1 = form.date1.value;
if (dat1.length != 10) return;
var dat2 = form.date2.value;
if (dat2.length != 10) return;
form.days.value = Math.floor((new Date(dat2)-new
Date(dat1))/(1000*60*60*24));
}
</script>
</head>
<body>
<form>
<select name="select_input">
<option value="1">1
<option value="2">2
</select>
<textarea name="text_area" cols="30" rows="10"></textarea>
<input type="button" onclick="append(this.form)">
<br><br>
<input type="text" name="date1" size="10" maxlength="10"
onchange="calc(this.form)">
<input type="text" name="date2" size="10" maxlength="10"
onchange="calc(this.form)">
<input type="text" name="days" size="5" maxlength="6" readonly> days
difference
</form>
</body>
</html>
 
R

RobG

Hi.

I know this is should be a simple question.

Questions are easy, it's the answers that cause headaches :)

[...]
I have done so far a little number of scripts that work well. But there
are two that I am having special difficulties with:
[...]

The practical part of your question (getting the content of form
elements and doing something with it) has been answered above.
The remaining issue is how to reliably capture dates entered by
a user.

You have two options:

1. Allow them to enter text and validate it thoroughly

2. Present a 'fool-proof' date picker that will only allow valid
dates to be entered.

The choice between the two depends on your users. If they are
entering lots of dates or reasonably computer and keyboard
literate, they will prefer to use option 1. If they are casual
users who only need to enter single dates infrequently, option
2 may suit better (or offer both).

Finally, never trust user-entered dates and always check the
content at the server.

Since no one has pointed you at Dr J's site for date stuff, here
it is:

<URL:http://www.merlyn.demon.co.uk/js-dates.htm>

Take the time to read and understand the issues here, I think
you'll find whatever you want.

A last word on date formats: the primary ISO standard is
yyyy-mm-dd, however other formats are suggested also.

Please read an excellent discussion of ISO8601 date/time formats
(recommended by the w3c) by Markus Kuhn here:

<URL:http://www.cl.cam.ac.uk/~mgk25/iso-time.html>
 
S

SGershon

Thanks McKirahan, for your help.
Thanks to everbody else that cared to reply as well.

The code you suggested worked perfectly by itself, but then I had a
little problems when using it in my page.
After a while, I managed to get the problems sorted.
The append is appending, and the days calculator is calculating.

I have a question on each function:
1) In the end of the append function, I do an text_area.focus(). It is
focusing, but the cursor stays at the first character.
How can I move the cursos to the end in order to make the user's work
easier (faster)?

2) I am having much trouble trying to use the dd/mm/yyyy format in the
date function.
Where can I set the "new date()" to use this format? I learned a
devguru.com that when building a date object from a string as we are
doing, it reads it in the format date.parse() tells. But I cannot see a
way to change from mm/dd/yyyy to dd/mm/yyyy!
Can you help me on this?

Thanks!
 
S

SGershon

Hi.

Thanks to everybody for the concerns.

I am using a date-picker to enter the date at the textboxes. Textboxes
are disabled to prevent direct editting.
Finally, never trust user-entered dates and always check the
content at the server.

I am checking the content by javascript at the client.
But now I am thinking (because you wrote "at the server"), that if the
user does not have javascript enabled I do not know what I am receiving
at the server... Is that why you said to check it at the server?
Also, if the user has JS disabled... he wont get the date-picker. Now
that I realised this my solution is to have the "disabled" text written
by a javacript document.write, cause I think this way user without JS
will have the textbox enabled. Is that right?
 
S

SGershon

Hi.

Thanks you all for the concerns.

I am using a date picker to insert the date in the textbox, and the
textbox is disable to prevent direct editting.

You said "always check content at the server".
I am checking content at the client using javascript.
But now that you said "at the server", I am thinking that if the user
has javascript disable, I will have no control over what I am
receiving. Is that why you said "at the server"?

Now that I think of it, the date-picker will not work if the user has
javascript disabled, and he can not edit the textbox content...
I am thinking... if I disable the textbox using javascript, users with
no javascript will have the textbox enabled. But is there a
"document.form.text_box.disabled" property?

SGershon
 
R

RobG

SGershon said:
Hi.

Thanks you all for the concerns.

I am using a date picker to insert the date in the textbox, and the
textbox is disable to prevent direct editting.

You said "always check content at the server".
I am checking content at the client using javascript.
But now that you said "at the server", I am thinking that if the user
has javascript disable, I will have no control over what I am
receiving. Is that why you said "at the server"?

There are two reasons to check at the server:

1. The user may have JS disabled (or their user agent may not
support JS at all)

2. The user can 'spoof' the data sent back to your server, that
is, the return may not come from your form at all but from
some contrived values the user has made up.

What you do about the above depends on your requirements. If
this is for a commercial web site, you must allow for both cases
above - non-JS users are about 10% of the surfer population
(this is a debatable statistic, but seems reasonable to me).

There is also likely a smaller but more troublesome element that
will try to break into your system using various techniques
based on spoofing the returned values.

OTOH, if this is for an intranet-only application where you can
specify JS to be enabled and have more control over users, the
first issue is still important but likely not quite as critical
(depending on your users, of course!). But the second is still
vital: you do not know who can get onto your network or
guarantee their behaviour.
Now that I think of it, the date-picker will not work if the user has
javascript disabled, and he can not edit the textbox content...
I am thinking... if I disable the textbox using javascript, users with
no javascript will have the textbox enabled. But is there a
"document.form.text_box.disabled" property?

Your date entry field should be enabled by default and disabled
by JS and replaced by the 'picker' functionality. Ideally, your
site should be just as usable without JS - JS should be used to
enhance functionality.

You can also use a date selector that doesn't rely on JS -
selects with options for year, month and day are common. You
can hide the selects with JS and use the picker, or if JS isn't
enabled, the selects are displayed.

Just don't treat your users like they are dumb - give them
information on how to use UI features before they have to find
out how they work by accident or trial and error. Stick to
conventions and standards wherever appropriate.

:)
 
R

RobG

SGershon wrote:
[...]
2) I am having much trouble trying to use the dd/mm/yyyy format in the
date function.

Here is a revised version of McKirahan's code that does some
date validation. It ensures things like month is between 1 & 12
inclusive and that the day is OK for the month (no November 31
or February 29 in non-leap years). For a reasonably complete
treatment of this topic, have a browse here:

<URL:http://www.merlyn.demon.co.uk/js-date4.htm#VID>

My routines are designed to be easily read, Dr J's stuff at the
above site is likely more efficient and thorough, but requires a
little more work to understand.

His site also has algorithms for date arithmetic:

<URL:http://www.merlyn.demon.co.uk/js-date1.htm>

Between Dr J's site and the script below, you should be able to
work out how to use any date format.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<title> Date Stuff </title>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<script type="text/javascript">

function calc(f) {
var d1 = validateDate(f.date1.value);
var d2 = validateDate(f.date2.value);

if ( d1 && d2 ){
var dat1 = new Date(d1[2],d1[1],d1[0]);
var dat2 = new Date(d2[2],d2[1],d2[0]);
} else {
// alert('Please enter valid dates');
f.days.value = 'Error';
return false;
}
f.days.value = Math.floor((dat2 - dat1)/(1000*60*60*24));
}
function validateDate(x){
var minYear = 2000;
var maxYear = 2010;

// Get the bits of the date
var d = x.split('-');
// Test year within range
if (d[2] < minYear || d[2]> maxYear) {
return false;
}
// Test month is between 1 and 12 inclusive
if (d[1] < 1 || d[1] > 12) {
return false;
// Test month is a 1 or 2 digit integer
} else if (! /\d{1,2}/.test(d[1])) {
return false;
}
// Test day is OK for month & year
if ( d[0] < 0 || d[0] > getMonthDays(d[2],d[1])) {
return false;
}
return d;
}

function getMonthDays(Y, M) {
return M==4 || M==6 || M==9 || M==11 ? 30 :
M==2 ? 28 + (Y%4==0 && ( Y%100!=0 || Y%400==0)) : 31 ;
}

</script>
</head>
<body>
<form>
<p>Please enter dates (dd-mm-yyyy):</p>
<input type="text" name="date1" size="10" maxlength="10"
onblur="calc(this.form)">&nbsp;Date&nbsp;1<br>
<input type="text" name="date2" size="10" maxlength="10"
onblur="calc(this.form)">&nbsp;Date&nbsp;2<br>
<input type="text" name="days" size="10" maxlength="6"
readonly>&nbsp;Difference&nbsp;(days)<br>
<input type="reset">
</form>
</body>
</html>
 
R

RobG

RobG wrote:

Aggghhh... perpetuated error, should have checked more
thoroughly:

[...]
if ( d1 && d2 ){
var dat1 = new Date(d1[2],d1[1],d1[0]);
var dat2 = new Date(d2[2],d2[1],d2[0]);

var dat1 = new Date(d1[2],d1[1]-1,d1[0]);
var dat2 = new Date(d2[2],d2[1]-1,d2[0]);

Must allow for JS dates that are 0 to 11. Sorry :-(
 
M

McKirahan

SGershon said:
Thanks McKirahan, for your help.
Thanks to everbody else that cared to reply as well.

The code you suggested worked perfectly by itself, but then I had a
little problems when using it in my page.
After a while, I managed to get the problems sorted.
The append is appending, and the days calculator is calculating.
I have a question on each function:
1) In the end of the append function, I do an text_area.focus(). It is
focusing, but the cursor stays at the first character.
How can I move the cursos to the end in order to make the user's work
easier (faster)?

function append(form) {
var what =
form.select_input.options[form.select_input.selectedIndex].value;
form.text_area.value += what;
var range = form.text_area.createTextRange();
range.collapse(false);
range.select();
}

Credit to Mark Honnen; perhaps an IE-only solution
2) I am having much trouble trying to use the dd/mm/yyyy format in the
date function.
Where can I set the "new date()" to use this format? I learned a
devguru.com that when building a date object from a string as we are
doing, it reads it in the format date.parse() tells. But I cannot see a
way to change from mm/dd/yyyy to dd/mm/yyyy!
Can you help me on this?

It's widely recommended that you use the unambiguous ccyy/mm/dd format.

You're welcome.
 
D

Dr John Stockton

JRS: In article <[email protected]>
, dated Mon, 14 Mar 2005 12:47:49, seen in (e-mail address removed) posted :
When any of the first two changes (to a date in the format
"dd/mm/yyyy"), the third one should contain the difference between the
dates, in days.

Any help with these?

Read the newsgroup FAQ.

Don't use dd/mm/yyyy in an international medium; use yyyy-mm-dd or
yyyy/mm/dd.

See below.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Mon, 14 Mar
2005 16:40:26, seen in McKirahan
Will this get you started? Watch for word-wrap.

That's your responsibility. Remember that if you hope to have more than
one reader it will be more efficient for you to get it right than for
your readers to have to detect and remove the errors that you would have
introduced. Ensure that what you transmit across the Net can be
executes in that state; readers then only have to avoid letting their
own systems introduce error.

This uses Mick White's formula for "days".

Don't publicly copy code that you have not tested yourself, adequately;
since most code is wrong, that wastes everybody's time.
var dat2 = form.date2.value;
if (dat2.length != 10) return;

That's a rather crude validation.
if (!/^\d\d\/\d\d\/\d{4}$/.test(dat2)) return
at least means, IIRC, that javascript will accept the value as some
date. For proper date validation, see the FAQ & below.
form.days.value = Math.floor((new Date(dat2)-new
Date(dat1))/(1000*60*60*24));

The OP specified dd/mm/yyyy. For at least some users, and I know of no
exceptions, new Date() will take it as being mm/dd/yyyy .

As a general rule, all code using 1000*60*60*24 is highly suspect. Not
that the product is intrinsically wrong; but those who are smart enough
to avoid the awaiting error will generally be smart enough to put 864e5
instead.

The rule holds in this case. Testing :
03/09/2005 04/09/2005 30 days difference
but March has 31 days
05/09/2005 06/09/2005 31 days difference
May also has 31 days

There will with that code be a visible error for every span that
includes more Springs than Autumns, and an invisible one for those with
the opposite unbalance, for many but not all users.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Tue, 15 Mar
2005 08:27:50, seen in McKirahan
It's widely recommended that you use the unambiguous ccyy/mm/dd format.

No, it is not.

It is widely recommended that yyyy-mm-dd be used, since that is the
International Standard; or yyyy/mm/dd because that's similar and
accepted directly by new Date().

I have heard that use of "ccyy" was specified in some organisation such
as the Texas Highway Patrol. Those are, evidently, educated persons who
know that the 20th century was 1901-2000 (or possibly they thought that
it was 1900-1999), and they therefore entered the number of the century
followed by the two-digit number of the year within the century.
Therefore, they were issuing tickets for dates 100 years ahead ...


But it could be worse; I have heard that IBM uses a ccyy such that the
1900s have CC=0 ....

Stick to yyyy; ccyy has no advantages.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Tue, 15
Mar 2005 07:33:16, seen in RobG
SGershon wrote:
[...]
2) I am having much trouble trying to use the dd/mm/yyyy format in the
date function.

Here is a revised version of McKirahan's code that does some
date validation.

Validation using RegExp and a Date Object is MUCH shorter and more
complete; your code accepts 1-3-2000-9 happily, and gives a difference
of NaN for 1-3-2000k9 and for 21-O4-2000 [*]

(After the M-1 correction -)

It also accepts 00-02-2000 & 00-03-2000, giving a difference of 29.

Your DateStr "dd-mm-yyyy" has the advantage that the result of
new Date(DateStr) will not be able to be attempted to be believed.

Your code gives me 30 days from 21-03-2005 to 21-04-2005. I expect that
it will give you 31 days for those dates. You could try 21-10-2005 to
21-11-2005, for which the correct answer is again 31 days; I have a
suspicion that you will also get 31 (Que?); but I expect ACT to get 30.
Tasmaniacs should try a month earlier, AIUI.

It gives me 1460 days from 28-03-2002 to 28-03-2006, whereas *between*
1900 and 2100 there are 1461 days per quadrennium. It will give you and
the Americans 1461, but for somewhat different reasons.


[*] Wherever a number may reasonably contain the digit zero, entry of
either O or o should not give an unduly confusing result!
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated
Mon, 14 Mar 2005 15:39:58, seen in kaeli

That page is Copyright 1999-2005 by Refsnes Data. Therefore, it really
ought to be correct by now. It is not.

Ignoring follies such as writing "The getUTCDate method returns the
Universal Coordinated Time", I see the following clear errors :


"milliseconds - the number of milliseconds since 01 January, 1970
00:00:00" - needs GMT.

"yr_num, mo_num, day_num - the year, month or day of the date" - is it
not mo_num-1 ?

"getFullYear() Returns the year of a Date object (four digits)" - no, it
returns a Number in the range -271821-04-20 to +275760; if the Date
Object represents a date in 1000-9999, that Number requires a four-digit
string.

"getYear() Returns the year of a Date object (from 0-99). Use
getFullYear instead !!" - Generally only 0-99 for 1900-1999

"getTime() Returns the number of milliseconds since midnight 1/1-1970" -
again two errors : needs GMT, and which midnight?

"getTimezoneOffset() Returns the time difference between the user's
computer and GMT" - does not state units, does not define sign clearly.

"getUTCFullYear() Returns the four-digit year of a Date object in
universal time" - not necessarily four.

"parse() Returns a string date value that holds the number of
milliseconds since January 01 1970 00:00:00" - needs GMT; in IE4 at
least, gives a Number.

"setFullYear() Sets the year in the Date object (four digits) - not
necessarily four, and more parameters can be given.

"setHours() Sets the hour in the Date object (from 0-23)" - more
parameters can be given.

"setYear() Sets the year in the Date object (00-99)" - actually sets
1900-1999 for that; other values in range set properly.


I may have missed some.


As a response to a memory test, it's not bad; but as a reference
document it is inadequate.

BTW, it only refers to NN & IE; no reference to others.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top