473,769 Members | 5,846 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Check numbers entered

I am constructing an HTML questionnaire and one of the questions
requires people to rate some choices from 1 to 5, where 1 is their
favourite and 5 is their least favourite:

Car
Bus
Taxi cab
Train
Airplane

Each choice has an INPUT TYPE=TEXT tag to contain the response. I
also have a function that is called ONCHANGE in order to check that a
number is entered between 1 and 5:

function CheckNos(obj) {
if(obj.value.ma tch(/[^\d]/) || obj.value<1 || obj.value>5)
{alert("Please enter a number between 1 and 5");obj.value=" ";return
false}
}

This works fine, but ideally I would like a function that could check
ONCHANGE that someone has not filled in the same number twice, for
example answered "1" for all of them. They are only allowed to use
each rating number once, so rating their choice 1 to 5.

Can anyone suggest a short function that could accomplish this easily?
Could I use some kind of array with 5 elements and allocate a flag
value once that number had been chosen, then check that the value had
been set?

I don't have a large amount of experience in Javascript so perhaps
someone could help me.

Thanks

Steve Wylie
United Kingdom
Jul 23 '05 #1
5 6319
Lee
Steve Wylie said:

I am constructing an HTML questionnaire and one of the questions
requires people to rate some choices from 1 to 5, where 1 is their
favourite and 5 is their least favourite:

Car
Bus
Taxi cab
Train
Airplane

Each choice has an INPUT TYPE=TEXT tag to contain the response. I
also have a function that is called ONCHANGE in order to check that a
number is entered between 1 and 5:

function CheckNos(obj) {
if(obj.value.m atch(/[^\d]/) || obj.value<1 || obj.value>5)
{alert("Plea se enter a number between 1 and 5");obj.value=" ";return
false}
}

This works fine, but ideally I would like a function that could check
ONCHANGE that someone has not filled in the same number twice, for
example answered "1" for all of them. They are only allowed to use
each rating number once, so rating their choice 1 to 5.

Can anyone suggest a short function that could accomplish this easily?
Could I use some kind of array with 5 elements and allocate a flag
value once that number had been chosen, then check that the value had
been set?


I'll assume that this is not a class assignment.

Since the elements of the form are accessible as an array, you don't
need to create a new one. If each entry is checked as it is changed,
the only possible source of duplication is for this new value to be
a duplicate of one existing value. All you need to do is to check
each other member of this ranking group against this new value.

Here's a simple (not completely idiot-proof or the most efficient)
solution that's flexible enough to use more than once in the same
form with a different number of members in each ranking group:

<html>
<head>
<script type="text/javascript">
function checkRank(box,f irstName,count) {

// *box* is the text field whose onChange handler called us.
// *firstName* is the name of the first field in this rank group.
// *count* is the number of items being ranked.
// Note that *count* must be less than 10.
//
// Check that text field *box* has a value from 1 to *count*,
// then check *count* text fields beginning at *firstName*,
// ensuring that no other field has the same value as *box*.
var errMsg="Please enter a digit 1-"+count+"\n "
+"that has not been used previously."

box.value=box.v alue.replace(/\s*/g,""); // remove spaces

if(!box.value.s earch(/^$/)) return; // this change is a deletion

if(box.value.se arch(new RegExp("^[1-"+count+"]$"))){
alert(errMsg);
box.value="";
return;
}

var group=box.form. elements;

for(var i=0;i<group.len gth;i++){
if(group[i].name==firstNam e){
firstIndex=i;
break;
}
}
var firstIndex=i; // will be group.length if no match

if(firstIndex+c ount-1>group.length) {
alert("Bad arguments! Fire the web designer!");
return;
}

for(var i=0;i<count;i++ ){
if(group[firstIndex+i]!=box &&
group[firstIndex+i].value==box.val ue){
alert(errMsg);
box.value="";
return;
}
}

}
</script>
</head>
<body>
<form>

<table>
<tr>
<td align="right">C ar</td>
<td><input name="car" size="3" onchange="check Rank(this,'car' ,5)"></td>
</tr>
<tr>
<td align="right">B us</td>
<td><input name="bus" size="3" onchange="check Rank(this,'car' ,5)"></td>
</tr>
<tr>
<td align="right">T axi cab</td>
<td><input name="taxi" size="3" onchange="check Rank(this,'car' ,5)"></td>
</tr>
<tr>
<td align="right">T rain</td>
<td><input name="train" size="3" onchange="check Rank(this,'car' ,5)"></td>
</tr>
<tr>
<td align="right">A irplane</td>
<td><input name="plane" size="3" onchange="check Rank(this,'car' ,5)"></td>
</tr>
</table>
<input type="reset" value="clear">
</form>
</body>
</html>

<html>
<head>
<script type="text/javascript">
function checkRank(box,f irstName,count) {

// *box* is the text field whose onChange handler called us.
// *firstName* is the name of the first field in this rank group.
// *count* is the number of items being ranked.
// Note that *count* must be less than 10.
//
// Check that text field *box* has a value from 1 to *count*,
// then check *count* text fields beginning at *firstName*,
// ensuring that none has the same value as *box*.

var errMsg="Please enter a digit 1-"+count+"\n "
+"that has not been used previously."

box.value=box.v alue.replace(/\s*/g,""); // remove spaces

if(!box.value.s earch(/^$/)) return; // change is a deletion

if(box.value.se arch(new RegExp("^[1-"+count+"]$"))){
alert(errMsg);
box.value="";
return;
}

group=box.form. elements;

for(var i=0;i<group.len gth;i++){
if(group[i].name==firstNam e){
firstIndex=i;
break;
}
}
var firstIndex=i; // will be group.length if no match

if(firstIndex+c ount-1>group.length) {
alert("Bad arguments! Fire the web designer!");
return;
}

for(var i=0;i<count;i++ ){
if(group[firstIndex+i]!=box &&
group[firstIndex+i].value==box.val ue){
alert(errMsg);
box.value="";
return;
}
}

}
</script>
</head>
<body>
<form>

<table>
<tr>
<td align="right">C ar</td>
<td><input name="car" size="3" onchange="check Rank(this,'car' ,5)"></td>
</tr>
<tr>
<td align="right">B us</td>
<td><input name="bus" size="3" onchange="check Rank(this,'car' ,5)"></td>
</tr>
<tr>
<td align="right">T axi cab</td>
<td><input name="taxi" size="3" onchange="check Rank(this,'car' ,5)"></td>
</tr>
<tr>
<td align="right">T rain</td>
<td><input name="train" size="3" onchange="check Rank(this,'car' ,5)"></td>
</tr>
<tr>
<td align="right">A irplane</td>
<td><input name="plane" size="3" onchange="check Rank(this,'car' ,5)"></td>
</tr>
</table>
<input type="reset" value="clear">
</form>
</body>
</html>

Jul 23 '05 #2
Hi Lee

Thanks for replying with your suggested script. It actually kills 3 birds
with one stone as I notice it also checks that the entry is a valid number
and also that it is within the specified range, so that eliminates the need
for me to use my existing function just to do that on its own.

I'll have to wait till I get back to work on Thursday to try it out on my
actual questionnaire.

No, it's not a school assignment(!) I work for a local government authority
in south-east England and your script will be used in the client-side
validation of one of our consultation questionnaires we put out, asking
residents in our district their views on crime, licensing laws and fire
safety. So all pretty worthwhile stuff I think you'll agree. Think I'll
put a comment line at the top of your function, "This script by Lee", not
that anyone will see it unless they look at the source!

Thanks again for your assistance.

Steve Wylie
Jul 23 '05 #3
JRS: In article <f2************ **************@ posting.google. com>, seen
in news:comp.lang. javascript, Steve Wylie <st*****@hotmai l.com> posted
at Tue, 22 Jun 2004 05:17:45 :
I am constructing an HTML questionnaire and one of the questions
requires people to rate some choices from 1 to 5, where 1 is their
favourite and 5 is their least favourite: Each choice has an INPUT TYPE=TEXT tag to contain the response. I
also have a function that is called ONCHANGE in order to check that a
number is entered between 1 and 5:
function CheckNos(obj) {
if(obj.value.m atch(/[^\d]/) || obj.value<1 || obj.value>5)
{alert("Plea se enter a number between 1 and 5");obj.value=" ";return
false}
}
Between 1 & 5, the only integers are the digits 2 3 4.

function CheckNos(obj) {
if (!obj.value.mat ch(/^[1-5]$/)) {
alert("Please enter a digit in 1 to 5") ;
obj.value="" ;
return false }
return true }

function CheckNos(obj) {
var OK = (obj.value.matc h(/^[1-5]$/))
if (!OK) {alert("Please enter a digit in 1 to 5") ; obj.value="" }
return OK }
This works fine, but ideally I would like a function that could check
ONCHANGE that someone has not filled in the same number twice, for
example answered "1" for all of them. They are only allowed to use
each rating number once, so rating their choice 1 to 5.

Can anyone suggest a short function that could accomplish this easily?
Could I use some kind of array with 5 elements and allocate a flag
value once that number had been chosen, then check that the value had
been set?


Better to check on finished, since it is legitimate to put 1 2 3 1 5
then change the first one to a 4.

If you check the product for being 120, I think only 2 2 2 3 5 permuted
will falsely pass. If you check also that the sum is 15 ... .

Number them 1 2 3 5 7, check with /^[12357]$/, and you need a product of
210, which no other combination of 1 2 3 5 7 can give.

The following should work, more generally :
var A = [] // an empty array
for each entry, get value V, then A[V] = 1
check that A[1]..A[5] all exist.
or
var A = []
for each entry, get value V, then A[V] = '#'
OK = A.join('').leng th==5

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #4
Thank you for your response, Dr John, but I think I'll stick with
Lee's suggestion because I can't understand your number play!
(Grade 4 CSE Maths, mate - this isn't my forté!)

Thanks anyway.

Steve
Jul 23 '05 #5
JRS: In article <f2************ **************@ posting.google. com>, seen
in news:comp.lang. javascript, Steve Wylie <st*****@hotmai l.com> posted
at Thu, 24 Jun 2004 02:45:10 :
Thank you for your response, Dr John, but I think I'll stick with
Lee's suggestion because I can't understand your number play!
(Grade 4 CSE Maths, mate - this isn't my forté!)


The paragraphs containing the numbers 120 & 210 only require what in my
time was taught to eight-year-olds; I don't know what CSE requirements
are.

For a set of numbers in 1..5 to multiply to 120 they must contain one 5,
and the others must make 24. To make 24, there must be a 3, and the
others must make 8. 8 can only be made as 4*2*1 and 2*2*2.

To get 210 by multiplying five numbers selected from 1 2 3 5 & 7, there
must be a 7, a 5, a 3, a 2 and a 1 (7 5 3 2 have no common factors).

The following paragraphs of that article show what should be the
shortest and most efficient check for the general case; but of course
they are a component rather than a fully-built answer.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
5267
by: Earl | last post by:
I'm curious if there are others who have a better method of accepting/parsing phone numbers. I've used a couple of different techniques that are functional but I can't really say that I'm totally happy with either. 1. My first technique was to restrict the users to entries that could only be 3 character, 3 characters, 4 character (area code, prefix, suffix, respectively). I would null out any inputs that were non-numeric (except the...
2
1355
by: savvy | last post by:
I'm developing a jobsite in which i'm working on Job Posting section. When the job is posted by the employer or any other agency they need to fill in all the related details in the respective textboxes. In the job description section i've provided a multiline textbox, in which i want to avoid them using telephone numbers and any http links. So, how can i make a check whether they have entered any phone numbers or links in the text. Any...
14
2349
by: Ørjan Langbakk | last post by:
I have a form where the user has the possibility to enclose his name. email, address and phonenumber. I want to be able to check if some of the fields are filled - at least one. This is so that we have some way to contact the customer. Today I check for the existence of an email-address, and a validation code - what I need is a way to check, eg. whether email _or_ phone is entered, and if none is entered, display an errorpage.
4
3688
by: John Salerno | last post by:
My code is below. The main focus would be on the OnStart method. I want to make sure that a positive integer is entered in the input box. At first I tried an if/else clause, then switched to try/except. Neither is perfect yet, but I was wondering which I should try for in the first place. I figure I need to check for an emptry string, non-numeric strings (maybe these are the same check), 0 and negative numbers (which might also fall into...
19
108018
Frinavale
by: Frinavale | last post by:
Filtering user input is extremely important for web programming. If input is left unfiltered users can input malicious code that can cripple your website. This article will explain how to make sure that the user only submits a number to your .NET web application and also demonstrate how to add JavaScript to your ASPX pages. Upon popular demand, I have added a section that also covers how to use a validator control to check if a text box...
9
2781
by: eggie5 | last post by:
How would I check if a string is a number? e.g: 'asdf2' =false '34' =true 'asf' =false '0' =true
3
1860
by: powerej | last post by:
writing a program that asks how many numbers the users want to enter, then input an integer for the amount of numbers said, output: number of integers entered, sum of them, average of them, maximum value entered and min value entered. the min is where i am having a problem i can get everything else to print out but i am doing something wrong in my while loop can someone please help me. import javax.swing.*; // gets option pane ...
39
2120
by: emre esirik(hacettepe computer science and enginee | last post by:
int n_mines; printf("How many mines do you want in the minefield?"); scanf("%d", &n_mines); while(n_mines>100 || n_mines<0) { printf("Please only enter between 1 and 100"); scanf("%d", &n_mines); }
4
1432
by: beginers of c | last post by:
hai friends see i have to get numbers in this manner 3 4 5 6 7 8 9 ok.And also my numbers should not be larger than 9.so for each number the condition has to be checked if it's great than 9 , then the pgm should return 0. for above pgm when 3 is entered the condition should be checked,if it's correct then i should be allowed to enter the next number.
0
9586
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10210
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10043
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8869
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.