By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,278 Members | 1,142 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,278 IT Pros & Developers. It's quick & easy.

Counting commas within a string

P: n/a
Hello:

I have a form that contains a multiple-select field that has 12
options in it. I would like the user to be able to select UP TO FOUR
of those options. If they select more than four, I would like to alert
them of the error. To do this, I figure that counting commas would be
the easiest method (i.e., IF commas > 3 THEN alert user).

NOTE: I have an existing "validateForm" function for this form and I'd
like to add this IF-THEN STATEMENT to it.

Any assistance is much appreciated. Also, if there's a better method
than "comma counting" I'm all ears. :)

Thanks,
Mike
Jul 23 '05 #1
Share this Question
Share on Google+
14 Replies


P: n/a
*Mike N.* wrote in comp.lang.javascript:
Hello:

I have a form that contains a multiple-select field that has 12
options in it. I would like the user to be able to select UP TO FOUR
of those options. If they select more than four, I would like to alert
them of the error. To do this, I figure that counting commas would be
the easiest method (i.e., IF commas > 3 THEN alert user).

NOTE: I have an existing "validateForm" function for this form and I'd
like to add this IF-THEN STATEMENT to it.

Any assistance is much appreciated. Also, if there's a better method
than "comma counting" I'm all ears. :)


Assuming 'strValue' is the CSV string you describe above, then:

var intNumFields = strValue.split(",").length;

This value is the number of selections you have, rather than the number
of commas between them.

// E.g.:
var MAXFIELDS = 4;

if (intNumFields > MAXFIELDS) {
alert("Sorry, please select up to a maximum of " + MAXFIELDS + "
choices")
return false;
}
--
Andrew Urquhart
- FAQ: http://www.jibbering.com/faq/
- Archive: http://groups.google.com/groups?grou...ang.javascript
- Contact me: http://andrewu.co.uk/contact/
Jul 23 '05 #2

P: n/a
Thanks for the prompt response!

Unfortunately, it's not working for me. Basically, no matter how many I
select (one, five, or all) it skips this code (not finding an error I
guess).

Are you sure this line is correct?

var intNumFields = strValue.split(",").length;

I am not familiar with the ".length" portion of it.

Thanks again!

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #3

P: n/a
*Mike N.* wrote in comp.lang.javascript:
Thanks for the prompt response!

Unfortunately, it's not working for me. Basically, no matter how many I
select (one, five, or all) it skips this code (not finding an error I
guess).

[snip]

Please post an example URI of it not working - there's likely another
problem.
--
Andrew Urquhart
- FAQ: http://www.jibbering.com/faq/
- Archive: http://groups.google.com/groups?grou...ang.javascript
- Contact me: http://andrewu.co.uk/contact/
Jul 23 '05 #4

P: n/a

I can't post a URL at this time (I'm assuming that is what you meant).
This is a members-only corporate site. I will rig something on a public
server as soon as I can...I'm in no rush at this point.

Thanks
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #5

P: n/a
On 15 Sep 2004 21:01:14 GMT, Mike N. <mn****@novationco.com> wrote:
I can't post a URL at this time (I'm assuming that is what you meant).
A URI is a Uniform Resource Identifier, as opposed to a Uniform Resource
Locator. The former is more abstract.
This is a members-only corporate site. I will rig something on a public
server as soon as I can...I'm in no rush at this point.


It doesn't need to be an actual page. If anything, that might complicate
the issue. All you need to show is a reduced version that replicates what
the page *does* and shows the error.

Regarding your question about the length property, the String.split method
take a String object and creates an array using the parameter supplied as
a delimiter. So,

'Element1,Element2,Element3'.split(',')

would return an array with three elements. It's now probably obvious that
the length property yields the number of elements in the generated array.

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #6

P: n/a

"Mike N." <mn****@novationco.com> wrote in message
news:17*************************@posting.google.co m...
Hello:

I have a form that contains a multiple-select field that has 12
options in it. I would like the user to be able to select UP TO FOUR
of those options. If they select more than four, I would like to alert
them of the error. To do this, I figure that counting commas would be
the easiest method (i.e., IF commas > 3 THEN alert user).

NOTE: I have an existing "validateForm" function for this form and I'd
like to add this IF-THEN STATEMENT to it.

Any assistance is much appreciated. Also, if there's a better method
than "comma counting" I'm all ears. :)
keep the ears get rid of the commas
the code below was tested in IE5.0.
<HTML><HEAD><TITLE>Multi Select</TITLE>
<script type=text/javascript>
function validate() {
var counter=0, a=document.forms[0].elements["oSelect"];
for (var i=0;i<a.length;i++)
if(a.options[i].selected==true)
if(++counter>=3) alert("STOP");
}
</script>
</HEAD>
<BODY>
<FORM>
<SELECT ID="oSelect" NAME="Cars" MULTIPLE onchange="validate()">
<OPTION VALUE="1" SELECTED>BMW
<OPTION VALUE="2">Porsche
<OPTION VALUE="3">Mercedes
<OPTION VALUE="4">Ferrari
<OPTION VALUE="5">Peugot
</SELECT></FORM>
</BODY></HTML> Thanks,
Mike

Hope this helps
Jimbo

Jul 23 '05 #7

P: n/a
Thanks Jimbo! That works very well.

Would there be any way that the function could also keep a +4 option
from being select after the user is alerted? For example, if the user
selects more options after an alertbox displays, even though they will
be alerted again the +4 options remain selected after all of the
alertboxes are extinguished.

I know that web users can be an adventurous lot sometimes. I really need
to ensure that there are no more than four options selected before they
can submit the form.

Thanks All!

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #8

P: n/a
Lee
Mike N. said:
I know that web users can be an adventurous lot sometimes. I really need
to ensure that there are no more than four options selected before they
can submit the form.


It's (nearly?) impossible to ensure that.

You absolutely must also check the data on the server side, as well.
Some will have javascript enabled. Some will construct their own
forms that submit to your server. Some will override your validation
function.

I've done all three to get around validations that annoyed me.

By the way, don't give up on using the much simpler "split"
method. Whoever has to maintain this page in the future will
appreciate it.

Jul 23 '05 #9

P: n/a
JRS: In article <17*************************@posting.google.com> , dated
Wed, 15 Sep 2004 11:50:26, seen in news:comp.lang.javascript, Mike N.
<mn****@novationco.com> posted :
I have a form that contains a multiple-select field that has 12
options in it. I would like the user to be able to select UP TO FOUR
of those options. If they select more than four, I would like to alert
them of the error. To do this, I figure that counting commas would be
the easiest method (i.e., IF commas > 3 THEN alert user).

The simple method, which combines brevity with not creating many
intermediate objects, is

var CommaCount = myString.replace(/[^,]/g, "").length
if ( CommaCount > 3 ) { OUCH! }

See <URL:http://www.merlyn.demon.co.uk/js-valid.htm#CCh> ; and the rest
of the page.

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

P: n/a
Thanks Lee!

When using the split(), wouldn't that also require looping through the
array of values created by the multiple-select field?

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #11

P: n/a
Well, I have the split() working, but only with a hardcoded value (e.g.,
"Option1, Option2, Option3, Option4"). When I attempt to insert the
value from the form field by replacing the above with...

var value = document.form.myOptions.value

...it doesn't work. Shouldn't the form field value be in the same
comma-separated format?

Please forgive my ignorance here. I am an HTML/ASP web developer and
rarely use JS.

Thanks
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #12

P: n/a
*Mike N.* wrote in comp.lang.javascript:
Hello:

I have a form that contains a multiple-select field that has 12 options in it. I would like the user to be able to select UP TO FOUR of those options. If they select more than four, I would like to alert them of the error. To do this, I figure that counting commas would be the easiest method (i.e., IF commas > 3 THEN alert user).

Then later wrote:Mike N. wrote:
Well, I have the split() working, but only with a hardcoded value (e.g.,
"Option1, Option2, Option3, Option4"). When I attempt to insert the
value from the form field by replacing the above with...

var value = document.form.myOptions.value

[snip]

I dont' get this!! What the OP really wants is a way of
seeing how many options have been selected - counting commas
is just the broken way he'd decided to do it.

Mike, just read the selected options into an array (which
has to be done anyway to do further processing) then find
the length of the array. Try this:

<script type="text/javascript">
/* Gets VALUES of selected options */
function getSelectedValues(a) {
var r = new Array();
for (var i = 0; i < a.options.length; ++i) {
if (a.options[i].selected) {
r[r.length] = a.options[i].value;
}
}
return r;
}
/* Does the validation */
function validate(theItem) {
var x = getSelectedValues(theItem);
if (x.length >= 3) {
alert(x + ' is too many');
theItem.form.reset();
} else {
alert('You selected ' + x.length);
}
}
</script>
<form name="fred" action="">
<select id="oselect" name="cars" multiple
onchange="validate(this)">
<option value="1" selected>BMW
<option value="2">Porsche
<option value="3">Mercedes
<option value="4">Ferrari
<option value="5">Peugot
</select><br>
<input type="reset">
</form>

Couple of tips:
1.
Pass a reference to the form or form element your script,

onchange="validate(this)"

that way you don't have to guess where the original form
came from. Using:

a=document.forms[0].elements["oSelect"];

will break as soon as you put another form above the current
form[0] - it will become form[1]. Passing a reference also
means you can do extra stuff, like reset() the form if the
user has done something silly (like try to by a Bimmer,
Merc, Ferrari and a Peugot).

2.
Note that I have selected values, not the text. You can get
the text by changing:

r[r.length] = a.options[i].value;
to
r[r.length] = a.options[i].text;

3.
Lastly, don't pester the user with alerts, I've used them
for the sake of this script.
Cheers, Rob.
Jul 23 '05 #13

P: n/a
RobG wrote:

[snip]
if (x.length >= 3) {


Aggghhh!!!! That should, of course, be:

if (x.length > 3) {

Cheers, Rob.
Jul 23 '05 #14

P: n/a
Rob,

Thanks so much! It's working well!

I appreciate all of the help from everyone!

Mike
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #15

This discussion thread is closed

Replies have been disabled for this discussion.