tags:

views:

27

answers:

3

I have for example: (111) 222-3333 - Verizon ... I want to when I select this fill in two text box. The first textbox having (111) 222-333 and in the second textbox with Verizon. Is this possbile with jquery?

A: 

Can you describe this a little more? What is the seperator here? If it's a ' - ' then you can do it in native JS using instr.

if the answer is all () and numbers are allowed in field 1 and everything past that is box two then maybe look at regular expressions to do the seperation where the numbers end.

edit

it is possible but you're parsing text and that's never nice. How about putting the number in an attribute and the carrier in another attribute and when you select the item pull them out using jquery's attr command?

griegs
@ griegs -- well, I have a selectlistbox, with phone numbers and carriers. What I would like to achive is when I select one of the number with carrier, I would like the first textbox to just show the phone number and the second textbox to show just the carrier. Is this possible with Jquery? If so, how would I resolve this?
hersh
+1  A: 

Sounds like the job for a regular expression:

var text = "(111) 222-3333 - Verizon";
var regexp = /(\(\d{3}\)\s\d{3}-\d{4}) - ([A-Za-z ]+)/;

result = regexp.exec(text);
if (result) {
    alert('Number: ' + result[1] + '\nCarrier: ' + result[2]);
}
else {
    alert('No match');
}

A bit of searching should turn up a more robust regular expressions to match phone numbers.

Also - you can use jQuery to help you move the result values around, i.e., $('#number_text_box').text(result[1]);, but the regular expression is a javascript thing, it doesn't depend on jQuery.


Update: this expression adds capturing groups, ( ) around each individual part of the number.

var regexp = /\((\d{3})\)\s(\d{3})-(\d{4}) - ([A-Za-z ]+)/;

You can then glue the numbers together:

var number = result[1] + result[2] + result[3];
var carrier = result[4];

A good place to experiment is in the browser itself - in Firebug or Webkit's console, you can run javascript like this directly to test it out.

Seth
@ Seth -- hey, your suggestion is great. Instead of returning (111) 222-3333, what about just 1112223333?
hersh
To do that, you would add more capturing groups, then join them together - see edit.
Seth
+1  A: 

Two way to do it, either you can use

var str="(111) 222-3333 - Verizo"
var result=str.split(" - ");
//var result[0] and result[1]

if you want to be more specifies with variable value you can use a nice jquery plugin in jquery created by James Padolsey that allows regex to be used for selection.

Say you have the following div:

<div class="asdf">
Padolsey's :regex filter can select it like so:

$("div:regex(class, .*sd.*)")

check documentation on selectors.

JapanPro