Pope
Pope

Reputation: 53

jquery to reformat the content of a textbox

can someone help me with a jquery script that reformat the word typed into a text box after the client has clicked on submit button. Thescript is to look through the words typed into a textbox, test if there is a a numeric value of 11 characters and then re-formats the numeric data by adding spaces after each 3 character of the numeric data e.g "We are inviting you for s special business meeting on Tueday, at No 12, Fred street. for more information please call 02341123333" This should be changed to "We are inviting you for s special business meeting on Tueday, at No 12, Fred street. for more information please call 023 411 233 33" Thank you

function Confirm() {

var data = $('#fix').val();

//check if numeric and 11 numbers
if (!isNaN(data) == true && data.length == 11) {

//show popup, if yes run the format function
if (window.confirm("Message contains numeric characters which might make the message not delivered to some networks. Do you want us to reformat the message ?. This might increase the numbers of pages of the message and the cost?")) {
  format(data);
}
} else {
 alert('Check number format'); 
}
}

function format(data) {

var first = data.substring(0, 4);
var second = data.substring(4, 20);
second = second.replace(/(.{3})/g, "$1 ")

$('#fix').val("This is my mobile number " + first + " " + second);

};

<script    src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="textbox" id="fix" name="fix" />
<button ID="button1" OnClick="Confirm();" runat="server">Confirm</button>

Upvotes: 0

Views: 26

Answers (1)

Anubhab
Anubhab

Reputation: 741

Here you go: https://jsfiddle.net/4j7t884u/. Basically look for and match 11 digits with regex, loop through and reformat the string and replace in original string.

var updateString = function(input_text){
     //1. Find consecutive 11 numeric digits
     var match = input_text.match(/\d{11}/);
     //2. divide it into a string of 3s separated by space
     var new_str = '';
     for(var i=1;i<match[0].length+1;i++){
         new_str = new_str + match[0][i-1];
       if(i>1 && i%3 == 0)
            new_str = new_str + ' ';
     }
     //3. Replace old match no. with the new one
     input_text = input_text.replace(match[0],new_str)
}

Upvotes: 1

Related Questions