View Full Version : detect/add character in input field?

Jul 2nd, 2007, 10:53 PM
hello, I'm not a JS expert, but is there any way to detect if there is a certain character at the ending of a sentence in a text input field?

for example, when a user puts "Hello, my name is Gary" into a certain text input with a specific ID and using the JS OnChange event, the script will add a period ( . ) if it is not detected.

or, when a period is detected at the end of the sentence ("Hello, my name is Gary."), it won't do anything.

I got this idea from reading the W3 School onchange doc, but I'm not sure if it's possible.


thanks in advance.

Jul 3rd, 2007, 12:18 AM
Try using lastIndexOf...here is a reference for more info.


Jul 3rd, 2007, 12:28 AM
erm, I don't know any JS at all, so I'm not sure how to incorporate the lastIndexOf thing.

Jul 3rd, 2007, 12:33 AM
Here's an example of using charAt:
<script type="text/javascript">
function ck(txt) {
if (txt.value.charAt(txt.value.length-1) != '.') {
txt.value = txt.value+'.';

<form id="myform" method="post" action="" enctype="multipart/form-data">
<input type="text" id="tfield" value="" size="50" maxlength="300" onchange="ck(this)" />

Jul 3rd, 2007, 01:12 AM
aha! that was what I was looking for. perfect, thanks.