Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 3 123 LastLast
Results 1 to 15 of 32
  1. #1
    Senior Coder
    Join Date
    Nov 2010
    Posts
    1,376
    Thanks
    263
    Thanked 32 Times in 31 Posts

    loop element verify integer value

    Hi this is my attempt at looping thru my input array and validating numeric only. it does not work of course lol..

    i am calling the function onsubmit from the form tag

    Code:
    Form input -  there are two elements so far in this array
    
    <input type="text" name="configvalue[]" id="configvalue" size="2" maxlength="2" value="<?=$c_value[$k];?>"/>
    and javascript

    Code:
    function validate_change()
    {
    
    var config = document.getElementByID("configvalue");
    
        //Loop through all form elements.
    
      for(var i = 0; i < config.elements.length; i++) 
      {
         //If the input form element is a text input not integer
         if(config.elements[i].type == "text" && parseInt(config.elements[i].value) != config.elements[i].value) 
          {
          alert("Number Only Please!");                                              
          return false;
          }
      }
     return true;
    }//close function
    Thanks

    I did find a few clues here in search so ill play a bit and see. I cant use form element because i dont want to check the whole form for integer just the one input


    Update i might be getting alittle closer i found somthing by Old Pedant and modified it, i think im alittle closer with this but not working yet..



    Code:
    function validate_change()
    {
    
    var confval[] = document.forms.advform.configvalue.value;
    
      for(var i = 0; i < confval.length; i++) 
      {
        var elem = confval[i];
    
         //If the input is a text input not integer
         if(elem.type == "text" && parseInt(elem[i].value) != elem[i].value) 
          {
          alert("Number Only Please!");                                              
          return false;
          }
      }
     return true;
    
    }//close function
    Last edited by durangod; 02-18-2013 at 07:05 PM. Reason: changed var confval = statment did some reading on forms lol

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,907
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Code:
    function validate_change() {  //prefer to place the opening brace on the same line
    
    var confval[] = document.forms.advform.configvalue.value;
    for(var i = 0; i < confval.length; i++)   {
    var elem = Number(confval[i]); 
    // If the input is not an integer number
    if ((isNaN(elem) || (parseInt(elem[i].value) != elem[i].value))   {
    alert ("Enter A Whole Number Only Please!");      
    document.forms.advform.configvalue.value  = "";  // clear the field 
    document.forms.advform.configvalue.focus(); // refocus on it                                
    return false;
    }
    }
     return true;
    
    }  //close function
    But that is a very long way round, and you can require a positive integer number much more simply by

    Code:
    <input type"text" name="NumsOnly" onblur="if(/\D/g.test(this.value)){alert('Only integer numbers are valid in this box.  '); this.value = ''; this.focus()}" />
    In other words, reject if any character but a digit (including a decimal point) is entered.

    If you prefer you can use onkeyup instead of onblur.

    Note:- alerts are regarded as obsolete and should only be used for testing purposes. Use DOM methods to display a message to the user.


    "There is hardly anything in the world that some man cannot make a little worse and sell a little cheaper, and the people who consider price only are this man's lawful prey." John Ruskin
    Last edited by Philip M; 02-17-2013 at 01:07 PM. Reason: Noticed typo

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    durangod (02-17-2013)

  • #3
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    The correct way to address a group of elements named "something[]" is as shown.

    Ideally you should pass a form reference to the function.

    Then you need some decent error checking. This requires all fields, but you weren't clear about that:

    Code:
    function validate_change()
    {
      var config = document.getElementById("IDofMyForm")[ "configvalue[]" ],
      error = false;
      
      for( var i = 0, elem; ( elem = config[ i ] ) && !error; i++ ) 
      {
         if( elem.type == "text" && ( !/\d/.test( elem.value ) || isNaN( elem.value ) ) ) 
         {
           alert("Number Only in each field Please!");                                              
           error = true;
         }
      }
      return !error;
    }

  • Users who have thanked Logic Ali for this post:

    durangod (02-17-2013)

  • #4
    Senior Coder
    Join Date
    Nov 2010
    Posts
    1,376
    Thanks
    263
    Thanked 32 Times in 31 Posts
    Thank you both very much, appreciate it. Philip do you see anything with yours that is not right. I cant see why i should not work i followed the logic and to me it should work but it does not toss up the alert.

    I did post logic ali and it worked (thank you for that Logic Ali ) but i am curious what i might be missing on philips that would cause it not to work (for learning purpose)

    Philip i also did some reading on W3C DOM wow interesting stuff, actually since most of my js is pretty standard stuff i rearly learn about dif ways and new stuff unless i have something special like this but DOM is def something to learn and i will try to use more of that as i go, thanks for that heads up


    I am also curious using Logic Ali method how i would go about clearing the indiv element [i] value

    i tried
    PHP Code:

    5 is the 
    default value

    document
    .getElementById("advform")[ "configvalue[i]" ].innerHTML '5';

    and 
    the normal 

    document
    .forms.advform.configvalue.value  '5'
    Last edited by durangod; 02-17-2013 at 09:50 PM.

  • #5
    Senior Coder
    Join Date
    Nov 2010
    Posts
    1,376
    Thanks
    263
    Thanked 32 Times in 31 Posts
    on alert maybe something like this. Does not work but am i on the right path here?

    PHP Code:
    elem.splice([i],1,'5'); 
    or                                        
    this.splice(elem,1,'5'); 
    one thing that makes this hard is that i cant see what im working with, since i guess there is no echo or print or print_r for js that i know of, if there is it would sure save me a load of time. I usually end up posting the var im working with to the alert itself so i can see it, but if there is a better way i would sure love to know about it, most times i fell like im flying blind, well actually i am..
    Last edited by durangod; 02-17-2013 at 10:39 PM.

  • #6
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    Quote Originally Posted by durangod View Post


    I am also curious using Logic Ali method how i would go about clearing the indiv element [i] value
    The correction to your line would be: document.getElementById("advform")[ "configvalue[]" ][ i ] = "5";

    To revise the function's logic:
    Code:
    function validate_change()
    {
      var config = document.getElementById("advform")[ "configvalue[]" ],
      error = false;
    
      for( var i = 0, elem; ( elem = config[ i ] ) ; i++ )
        if( elem.type == "text" && ( !/\d/.test( elem.value ) || isNaN( elem.value ) ) )
        {
          elem.value = elem.defaultValue;
          error = true;
        }
    
      if( error )
        alert( "Number Only in each field please!" );
    
      return !error;
    }

  • #7
    Senior Coder
    Join Date
    Nov 2010
    Posts
    1,376
    Thanks
    263
    Thanked 32 Times in 31 Posts
    thanks i was just playing around and got this to work


    i added

    Code:
    var defval = 5;  //def val 
    
    alert("Number Only in each field Please! You entered: " + elem.value);
    newval = document.getElementById('configvalue').value = defval;
    document.getElementById('configvalue').innerHTML = newval;
    now let me look and see what you posted in reply, thanks so much


    nice thanks Logic Ali

    The correction to your line would be: document.getElementById("advform")[ "configvalue[]" ][ i ] = "5";
    ahah! i was soooooooooo close, thanks so much
    Last edited by durangod; 02-17-2013 at 10:59 PM.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,121
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    This is *NOT* right:
    Code:
       if( elem.type == "text" && ( !/\d/.test( elem.value ) || isNaN( elem.value ) ) )
    That would accept an input of (for example) "-73.8881119931"

    The regular expression test there is only saying "find a digit *ANYWHERE* in elem.value". And then the isNaN() test does *NOT* reject negative or floating point numbers.

    If you want to accept only a *SINGLE DIGIT* then use:
    Code:
       if( elem.type == "text" &&  ! /^\d$/.test( elem.value )  )
    If you want to accept any number of digits, ONLY, then use:
    Code:
       if( elem.type == "text" &&  ! /^\d+$/.test( elem.value )  )
    or Philip's
       if( elem.type == "text" &&  /\D/.test( elem.value )  )
    The first says reject anything except "at the start of text find a single digit that then is also the end of text."
    The second is simpler: reject anything "that contains any non-digit character."

    If you want to accept, say, only numbers from 0 to 999, then use:
    Code:
       if( elem.type == "text" &&  ! /^\d{1,3}$/.test( elem.value )  )
    (You can change the 3 to accept any max number of digits, of course.)
    Last edited by Old Pedant; 02-17-2013 at 11:05 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    durangod (02-18-2013)

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,121
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    I have to ask a stupid question: WHY do you need to test for elem.type == "text"??

    SURELY you don't have any <form> fields with a name of "configvalue[]" that are *NOT* text fields?

    Heck, for that matter, couldn't you have just done
    Code:
        var config = document.getElementsByName( "configvalue[]" );
    ??
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #10
    Senior Coder
    Join Date
    Nov 2010
    Posts
    1,376
    Thanks
    263
    Thanked 32 Times in 31 Posts
    Quote Originally Posted by Old Pedant View Post
    I have to ask a stupid question: WHY do you need to test for elem.type == "text"??

    SURELY you don't have any <form> fields with a name of "configvalue[]" that are *NOT* text fields?

    Heck, for that matter, couldn't you have just done
    Code:
        var config = document.getElementsByName( "configvalue[]" );
    ??
    LOL are you asking Logic Ali or me lol... i just used it because it is what he suggested but you are so right lol.. how funny..

    And just on your prev post i do have the field limited to maxlength of 2 so 99 would be the max i would think, the input is the dynamic setting for 'records per page' and 'session timeout' in the conf table. So 99 rpp and 99 min session is more than enough i would think.


    @old pedant

    i chose this

    Code:
     if(! /^\d{1,2}$/.test( elem.value ) || isNaN( elem.value ) ) //changed to 2
         {
    
    
    
    but im curious are you saying i dont have to use 
    
    isNaN( elem.value )  at all.
    Last edited by durangod; 02-17-2013 at 11:27 PM.

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,121
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Okay, then use
    Code:
       if( ! /^\d\d?$/.test( elem.value )  )
    Which insists on one digit but allows another one.

    If you don't want to allow zero as an input, then you could get more creative:
    Code:
       if( ! /^[1-9]\d?$/.test( elem.value )  )
    That wouldn't allow inputs of "07" or "09", though. If you want to be really pedantic then:
    Code:
       if( ! /^(0[1-9]|[1-9]\d?)$/.test( elem.value )  )
    That allows 01 through 99, and numbers 1 through 9 are okay with or without the leading zero.

    (By the by, there is no point in the isNaN() test. If the input consists only of digits, then of course it is a number.)
    Last edited by Old Pedant; 02-17-2013 at 11:29 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,121
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    And I have to ask one more question: WHY do you name those two VERY DIFFERENT settings the same: "configvalue[]"???

    Why not give them names that reflect what they are?

    Code:
    <input name="recordsPerPage" />
    <input name="sessionTimeout" />
    ???

    Surely, in your PHP code, you just end up having to do something like:
    Code:
    $recordsPerPage = $_POST["configvalue"][0];
    $sessionTimeout = $_POST["configvalue"][1];
    No? So why not skip the ugly crap and just be able to do
    Code:
    $recordsPerPage = $_POST["recordsPerPage"];
    $sessionTimeout = $_POST["sessionTimeout"];
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #13
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    Quote Originally Posted by Old Pedant View Post
    This is *NOT* right:
    Code:
       if( elem.type == "text" && ( !/\d/.test( elem.value ) || isNaN( elem.value ) ) )
    That would accept an input of (for example) "-73.8881119931"
    Which I am given to understand is a number.
    If someone specifies the range and type of acceptable numbers, then it can be accommodated. I saw no such stipulation.

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,121
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    From first post in the thread:
    I cant use form element because i dont want to check the whole form for integer just the one input...
    ... && parseInt(elem[i].value) ...
    Granted, he never said negative values weren't allowed until much later.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #15
    Senior Coder
    Join Date
    Nov 2010
    Posts
    1,376
    Thanks
    263
    Thanked 32 Times in 31 Posts
    Quote Originally Posted by Old Pedant View Post
    And I have to ask one more question: WHY do you name those two VERY DIFFERENT settings the same: "configvalue[]"???

    Why not give them names that reflect what they are?

    Code:
    <input name="recordsPerPage" />
    <input name="sessionTimeout" />
    ???

    Because not only are the values dynamic but also the names associated are dynamic as well so there also be more additions to the config table like colors and other css dynamics to the table fields later so i wanted to be able to be set to do
    ["configvalue"][0]; //current value
    ["configvalue"][1]; //current value
    ["configvalue"][2]; and so on

    and also because i have always tried to do names that i know what they mean but they are not your straight forward var names, i got introuble one time by using a common name and it took me forever to figure out it as the name itself that was the issue, and i swore to never use a fairly common name again, this was back in the old days where we had to do our error control line by line because the system just said fail pretty much and did not really say where it failed.

    as i mentioned there are two arrays in the same form one for value and one for name so the form and array looks like this

    Code:
    <span class="tdeven">
    <input type="hidden" name="configname[]" id="configname" value="<?=$c_name[$k];?>" />
    <input type="text" name="configvalue[]" id="configvalue" size="2" maxlength="2" value="<?=$c_value[$k];?>"/>
    </span>

    PHP Code:

    Array 

        [
    configname] => Array 
            ( 
                [
    0] => Records Per Page 
                
    [1] => Session Timeout 
            


        [
    configvalue] => Array 
            ( 
                [
    0] => 15 
                
    [1] => 20 
            


        [
    csave] => csaved 
        
    [submit] => Submit 

    and then when i update the db i do it like this


    PHP Code:

    for ($i 0$i <= $elenum$i++)  
       { 
       
    $update="UPDATE config SET cvalue='$val_array[$i]' WHERE cname='$name_array[$i]'"
       
    $resu mysqli_query($myconnect$update); 
       } 
    because i didnt want to use id because the id could change and i actually just didnt feel like storeing the id and using it lol... I felt the name would be a better more reliable value to use to get the right update in the right place.



    as far as my function goes, here is what i have so far and i will make some notes on this inside the function to let you know where i am at.
    Code:
    function validate_change(){
    
      var defval = 5;
      var confv = document.getElementById("advform")[ "configvalue[]" ],error = false;
      
      for( var i = 0, elem; (elem = confv[ i ]) && !error; i++ ) 
      {
    
         if(! /^\d{1,2}$/.test( elem.value ) || isNaN( elem.value ) )
         {
           alert("Number Only in each field Please! You entered: " + elem.value);
    
          //this works but once the value is 5 (the default) it does return true 
    i guess because the form submits after i close the alert.  
    Which is ok i guess, at least it is posting the default value and not the chars, 
    but i am not sure why it auto submits when i close the alert. 
    
          newval = document.getElementById('configvalue').value = defval;
          document.getElementById('configvalue').innerHTML = newval;
    
           //removed the two above and tried to use this instead but did not work
           //document.getElementById("advform")[ "configvalue[]" ][i] = "5";
    
           error = true;
        
    
         }//close if
      }//close for loop
    
    return !error;
    
    
    }//close function validate_change
    //-->
    </script>
    also is there any reason i cant return true or false and i have to return error or ! error
    Last edited by durangod; 02-18-2013 at 12:08 AM.


  •  
    Page 1 of 3 123 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •