I can't add space

Hi, I need some help how can i add space if i will input numbers in textfield,I want that if the user will input 888 it will add space directly after the last 8 then if he will continue to add 4 digits 5555 it will add space after the last digit 5,can you help me please how can i achieve this.

my code is not working.


 $(function(){
             $('#txtno').keyup(function(e){
                 e.preventDefault();
                var counter = 0;
                var dgt = $(this).val();
                  if(counter == '3'){

                    dgt = $(this).val() + " ";
                  }else if(counter == '7'){
                     dgt = $(this).val() + " ";
                  }
                  else{
                      dgt = $(this).val();
                  }

                $(this).val(dgt);
                counter++;
              });
           });



Thank you in advance.:slight_smile:

Hi jemz,

Having read your code, it might be better to first take a step back and tell us what you are trying to achieve.

Obviously the user should input something, but what are the possible permutations?
Is text allowed, are numbers allowed?
What is it that the user is inputting? A serial number?

Hi pullo, a user will input mobile numbers and the format something like this 888 9256 269.

Hope this helps.:slight_smile:

Hey jemz,

So which characters are allowed in a mobile number on your page?
As an average user, I would expect to be able to enter:

+ - ( ) 1 2 3 4 5 6 7 8 9 0

What do you think?

Hi pullo,

only this

1 2 3 4 5 6 7 8 9 0
will be allowed,but if the user will input zero digit in the begining, this will not be allowed or will be disregard :slight_smile:

Thank you in advance.

Ok, so how long may the number be?
And where do you want spaces inserted?

10 digits only

where do you want spaces inserted?

Okay so if the user will input this mobile numbers.

8569236987

The spaces will be inserted on this

856space9236space987

hope this helps.

Thank you in advance.:slight_smile:

Ok, well this should demonstrate the basic concept:

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Validate phone number</title>
  </head>
  
  <body>
    <input type="text" id="mobileNo" maxlength="12" placeholder="Mobile number"/>
    

    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
    <script>
      String.prototype.insertAt=function(index, string) { 
        return this.substr(0, index) + string + this.substr(index);
      }  
        
      function digitPressed(event){
        var keyPressAcceptable = false;
        // Allow: backspace, delete, tab, escape, and enter
        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || 
          // Allow: Ctrl+A
          (event.keyCode == 65 && event.ctrlKey === true) || 
          // Allow: home, end, left, right
          (event.keyCode >= 35 && event.keyCode <= 39) || 
          // Allow: 0 - 9
          (event.keyCode >= 48 && event.keyCode <= 57)) {
          // let it happen, don't do anything
          keyPressAcceptable = true;
        }
        return keyPressAcceptable;
      }
      
      function formatNumber(el){
        var newValue = el.val().replace(/\\s+/g, '');
        if (newValue.length > 3){
          newValue = newValue.insertAt(3, " ");
        }
        if (newValue.length > 8){
          newValue = newValue.insertAt(8, " ");
        }
        el.val(newValue);
      }
      
      $("#mobileNo").keydown(function(event) {
        if (! digitPressed(event)){
          event.preventDefault();
        }
      });
      
      $("#mobileNo").keyup(function(event) {
        formatNumber($(this));
      });
    </script>
  </body>
</html>

Any questions, let me know.

References:
http://stackoverflow.com/questions/4364881/inserting-string-at-position-x-of-another-string
http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery

Hi pullo, Thank you for helping me,it works like a charm :slight_smile:

No problems!

If the format is very important to you, don’t forget to check it on the server, too, as someone with JS disabled could easily negate this.

Hi pullo,

Any questions, let me know.

can i ask about this code

String.prototype.insertAt=function(index, string) {
return this.substr(0, index) + string + this.substr(index);
}

Thank you in advance.

Sure, well this:

String.prototype.myFunction = function() {
  ...
}

is just a way of adding a function to the String class so that you so can use it on any String object.

And this:

return this.substr(0, n) + myVar + this.substr(n);

concatenates the first n characters of a string, a variable and the remaining n characters of the string, then returns it.

Is there one particular bit you don’t understand?

is just a way of adding a function to the String class so that you so can use it on any String object.

You mean you are making your own function for the Strings object ?

Hi pullo,

don’t forget to check it on the server

I am submitting my form via jquer.ajax,and in my adduser.php i made some serverside validation with my fields if there is a problem or an error the returned in my ajax will alert the error message.my question for this is this still prawn to tampering even though the returned error came from my server side ?


 var serializeform = $('#myform').serialize();
  $.ajax({
                     type: 'post',
                     data: serializeform,
                     url: "adduser.php",
                     success: function(data){
                      
                          if(data=="ok"){
                              //some of my script here.
                          }
                         else
                           alert(data);
                      }


                  });



Yes.

For example, imagine you wanted to extend the String class by a function that determined whether a given string contained a vowel.
You could do it like this:

String.prototype.containsVowel = function() {
  return this.match(/[aeiouAEIOU]/);
}

if("Pfffttth!".containsVowel()){
  console.log("Vowel found!");
} else {
  console.log("No vowels here. Move along!");
}

words = ["cat", "Dog", "rbbt", "fi$h", "xxxxxxxxxxx", "Pullo"];

words.map( function(word) {
  if (word.containsVowel()){
    console.log("Vowel found in " + word);
  }
});

It’s not prone to tampering if you check the input on the server.
However, if you rely solely on JS to display the errors, then anyone with JS turned off won’t know why their form didn’t submit if they don’t fill it out correctly.

Hi pullo, if the user will turn of the JS,what i want is that my server validation will take place,i mean it will prompt to the user so that the user will know there is an error in the form.,but i was worried my code because i am submitting the form through jquery.ajax,and i could not display the error message which is validated from the server…

Thank you in advance.

Hi pullo, I apologize ,i was not thinking that the JS is disabled and the user cannot submit the form…:slight_smile:

Thank you for helping me this thread :slight_smile:

No probs.

Just to elaborate on what I was saying though, in a perfect world you would create your form first and make sure that it submits properly.
Then you would add the AJAX functionality on top of that.

Here’s an example.

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>AJAX form demo</title>
    <style>
      div{ padding:5px; margin:5px; }
      .required {color: red; font-weight: bold; }
    </style>
  </head>

  <body>
    <form action="index.php" method="post">
      <div>
        <label for="name"><span class="required">*</span> Name:</label>
        <input type="text" name="name" id="name" />
      </div>
      <div>
        <input value="Submit" name="submit" type="submit" />
      </div>
    </form>
    <div id="results"></div>

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
      $("input:submit").on("click", function(e){
        e.preventDefault();
        var name = $("#name").val();

        $.ajax({
          type : "POST",
          url : "index.php",
          data: {name: name},
          success : function(res) {
            $("#results").html(res);
          }
        });
      });
    </script>
  </body>
</html>
<?php
$retVal = "";
$name = $_POST['name'];

if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
  $retVal .= "<p>Form submitted via AJAX</p>";
} else {
  $retVal .= "<p>Form submitted via POST</p>";
}

if ($name == ""){
  $retVal .= "<p>Name: left blank</p>";
  $retVal .= "<p>Please fill out your name and resubmit the form.</p>";
} else {
  $retVal .= "<p>Name: " . $name . "</p>";
  $retVal .= "<p>Thank you for submitting the form, " . $name ."!</p>";
}

echo $retVal;
?>

Here’s a demo.
The name field is required. Try submitting the form with and without JavaScript enabled.
Both should work.