Counting commas within a string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mike N.

    Counting commas within a string

    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 "validateFo rm" 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
  • Andrew Urquhart

    #2
    Re: Counting commas within a string

    *Mike N.* wrote in comp.lang.javas cript:[color=blue]
    > 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 "validateFo rm" 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. :)[/color]

    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/

    Comment

    • Mike N.

      #3
      Re: Counting commas within a string

      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!

      Comment

      • Andrew Urquhart

        #4
        Re: Counting commas within a string

        *Mike N.* wrote in comp.lang.javas cript:[color=blue]
        > 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).[/color]
        [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/

        Comment

        • Mike N.

          #5
          Re: Counting commas within a string


          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!

          Comment

          • Michael Winter

            #6
            Re: Counting commas within a string

            On 15 Sep 2004 21:01:14 GMT, Mike N. <mneely@novatio nco.com> wrote:
            [color=blue]
            > I can't post a URL at this time (I'm assuming that is what you meant).[/color]

            A URI is a Uniform Resource Identifier, as opposed to a Uniform Resource
            Locator. The former is more abstract.
            [color=blue]
            > 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.[/color]

            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,Eleme nt2,Element3'.s plit(',')

            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.

            Comment

            • J. J. Cale

              #7
              Re: Counting commas within a string


              "Mike N." <mneely@novatio nco.com> wrote in message
              news:17990171.0 409151050.14f9f 2f@posting.goog le.com...[color=blue]
              > 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 "validateFo rm" 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. :)[/color]

              keep the ears get rid of the commas
              the code below was tested in IE5.0.
              <HTML><HEAD><TI TLE>Multi Select</TITLE>
              <script type=text/javascript>
              function validate() {
              var counter=0, a=document.form s[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="valid ate()">
              <OPTION VALUE="1" SELECTED>BMW
              <OPTION VALUE="2">Porsc he
              <OPTION VALUE="3">Merce des
              <OPTION VALUE="4">Ferra ri
              <OPTION VALUE="5">Peugo t
              </SELECT></FORM>
              </BODY></HTML>[color=blue]
              > Thanks,
              > Mike[/color]
              Hope this helps
              Jimbo



              Comment

              • Mike N.

                #8
                Re: Counting commas within a string

                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!

                Comment

                • Lee

                  #9
                  Re: Counting commas within a string

                  Mike N. said:
                  [color=blue]
                  >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.[/color]

                  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.

                  Comment

                  • Dr John Stockton

                    #10
                    Re: Counting commas within a string

                    JRS: In article <17990171.04091 51050.14f9f2f@p osting.google.c om>, dated
                    Wed, 15 Sep 2004 11:50:26, seen in news:comp.lang. javascript, Mike N.
                    <mneely@novatio nco.com> posted :
                    [color=blue]
                    >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).[/color]


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

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

                    See <URL:http://www.merlyn.demo n.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.c om/faq/> JL/RC: FAQ of 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.

                    Comment

                    • Mike N.

                      #11
                      Re: Counting commas within a string

                      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!

                      Comment

                      • Mike N.

                        #12
                        Re: Counting commas within a string

                        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.m yOptions.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!

                        Comment

                        • RobG

                          #13
                          Re: Counting commas within a string

                          *Mike N.* wrote in comp.lang.javas cript:
                          [color=blue][color=green]
                          >> Hello:
                          >>
                          >> I have a form that contains a multiple-select field that[/color][/color]
                          has 12[color=blue][color=green]
                          >> options in it. I would like the user to be able to[/color][/color]
                          select UP TO FOUR[color=blue][color=green]
                          >> of those options. If they select more than four, I would[/color][/color]
                          like to alert[color=blue][color=green]
                          >> them of the error. To do this, I figure that counting[/color][/color]
                          commas would be[color=blue][color=green]
                          >> the easiest method (i.e., IF commas > 3 THEN alert user).[/color][/color]

                          Then later wrote:Mike N. wrote:
                          [color=blue]
                          > 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.m yOptions.value[/color]
                          [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 getSelectedValu es(a) {
                          var r = new Array();
                          for (var i = 0; i < a.options.lengt h; ++i) {
                          if (a.options[i].selected) {
                          r[r.length] = a.options[i].value;
                          }
                          }
                          return r;
                          }
                          /* Does the validation */
                          function validate(theIte m) {
                          var x = getSelectedValu es(theItem);
                          if (x.length >= 3) {
                          alert(x + ' is too many');
                          theItem.form.re set();
                          } else {
                          alert('You selected ' + x.length);
                          }
                          }
                          </script>
                          <form name="fred" action="">
                          <select id="oselect" name="cars" multiple
                          onchange="valid ate(this)">
                          <option value="1" selected>BMW
                          <option value="2">Porsc he
                          <option value="3">Merce des
                          <option value="4">Ferra ri
                          <option value="5">Peugo t
                          </select><br>
                          <input type="reset">
                          </form>

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

                          onchange="valid ate(this)"

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

                          a=document.form s[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.

                          Comment

                          • RobG

                            #14
                            Re: Counting commas within a string

                            RobG wrote:

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

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

                            if (x.length > 3) {

                            Cheers, Rob.

                            Comment

                            • Mike N.

                              #15
                              Re: Counting commas within a string

                              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!

                              Comment

                              Working...