0

in this code i want to have a 09 unchangeable in first textbox and after that i want to have certain dash and when i typed one number one of the dashes disappear . my problems is how can i do that with dashes when user types??

$('#PhoneField').val('---------09');


$("#PhoneField").keydown(function (e) {
          var inputValue = $(this).val();
          var inputObject = $(this);
          setTimeout(function () {
              if(inputObject.val().indexOf('09')!== 0){
                  inputObject.val('09');
              }

          })
})
sepehr
  • 165
  • 1
  • 2
  • 10
  • 1
    Please click the `<>` and create a [mvce] – mplungjan Oct 08 '17 at 14:13
  • 1
    Sounds like a duplicate of https://stackoverflow.com/questions/42172859/how-to-add-dashes-into-a-number-input-field-while-entering-the-number – mplungjan Oct 08 '17 at 14:13
  • I started working on a solution via [JSFiddle here](https://jsfiddle.net/5L3jbv41/3/), I hope this helps! – Nick Oct 08 '17 at 14:47
  • @snapjs hyphens are behind the 09 when typing and also i want 09 is unchangeable.please help tnx – sepehr Oct 08 '17 at 17:13
  • @sepehr I think I'm just misunderstanding what you're looking for. What would an example of a final number look like? – Nick Oct 08 '17 at 17:39
  • @snapjs i want to first of all . that textbox look like 09--------- . 09 is constant and unchangebale.and when i start typing numbers in textbox numbers replaces with hyphens one by one in front of 09 – sepehr Oct 08 '17 at 17:47
  • @snapjs sorry is it clear ? – sepehr Oct 08 '17 at 17:48
  • OK, so it first appears as 09--------. Then, when someone starts typing, let's say they type 1, would it look like 091--------? Also, would a final number look like 09123456789? – Nick Oct 08 '17 at 18:11
  • @snapjs exactly . would you tell me what is the code for that? – sepehr Oct 08 '17 at 18:18

1 Answers1

0

I believe the following code takes into account all of the requirements. Additionally, this can be viewed in action in JSFiddle here.

$("#PhoneField").val("09---------");

$("#PhoneField").keyup(function () {
  $("#PhoneField").val(function() {
      var phoneNumber = $(this).val().replace(/-/g, "");
      var curLength = phoneNumber.length;
      // Add correct number of hyphens to front of phone number
      var hyphens = Math.max(12 - phoneNumber.length, 0);
      phoneNumber = phoneNumber + Array(hyphens).join("-");
      // If the first characters are not 09, add them
      if(phoneNumber.substring(0, 2) !== "09") {
        phoneNumber = "09" + phoneNumber;
      }
      // Impose length limit
      phoneNumber = phoneNumber.substring(0,11);
      return phoneNumber;
  });
});
Nick
  • 16,066
  • 3
  • 16
  • 32