2

I add a string (i.e. 'Bob Smith') from a jQuery click event trapped using the on function . . .

$(".vendorLookup").on("click", { fullName: $(this).text() }, displayAddy);

In the displayAddy handler for the click event, I extract the string (a persons first and last name) and split out the first and last name . . .

var name = event.data.fullName;
var parts = name.split(" ");

IE can figure this one out but Chrome and Firefox will not split unless I use the regular expression split(/\s/) (unless I use the w3schools.com Tryit code editor and then it works).

Question: what exactly is going on here and when will I get bit by this later on when parsing for spaces cross-browser?

(Note: I don't think it matters but I am running this script on a wiki page in SharePoint 2010)

Toadmyster
  • 490
  • 3
  • 10
  • Split does work with a string. name.split(" "); is valid. – Diodeus - James MacFarlane Jan 17 '12 at 19:58
  • Since [this](http://jsfiddle.net/5MC2k/) bare bones example works in Firefox, Chrome, and IE, there must be something else going on since split() has no issues splitting on the space. Have you tried to log event.data.fullName to the browser? – j08691 Jan 17 '12 at 19:59
  • Can you provide one runnable sample? http://jsfiddle.net/ –  Jan 17 '12 at 20:00
  • 2
    `\s` matches all whitespace, so my guess is that you have a different whitespace character in your string than you think you do. – David Brainer Jan 17 '12 at 20:07
  • Good call, David! The SharePoint web editor converted the space to ` `. Sure enough, checking for a string literal space entered with the space bar doesn't match. If you want to submit an answer to that effect I'll mark it for you. I would still like to know why Chrome and FF can't figure it out whilst IE can. – Toadmyster Jan 18 '12 at 18:26

1 Answers1

1

I'm not sure whats going on (I tested it and see some weird behavior), but you can work around it by doing something like this

function displayAddy() {

    var parts = $(this).text().split(" ");

    $('#fname').html(parts[0]);
    $('#lname').html(parts[1]);
}

$('#name').on("click", displayAddy);

Since the event is being passed off to a callback the callback already has a this object. in this instance the this object is going to be DOM object with the class #name.

Here's an example of it in action.

Brombomb
  • 6,988
  • 4
  • 38
  • 57
  • Thanks, Brombomb but the problem is in the html and the way browsers interpret the space character (see my comment in the original post and David's above). I already had a workaround which was to use the reg expression `\s` instead of a literal space. – Toadmyster Jan 18 '12 at 18:31