digitalpixelpro
digitalpixelpro

Reputation: 139

jQuery .text() returned string isn't behaving like string

I am working in a backbone.js in coffeescript and I am trying to select a model out of a collection using the 'where' function. I am passing in a string variable as the second argument and the string is assigned by the return of a jQuery .text() function on a span element.

I do get a string out of the .text() function, but it isn't behaving like a normal string. I can only use a variable as a where() argument if I assign it manually.

Edit: I changed $('e.target') to $(e.target), turns out that what I actually have in my gist. I just mis-typed it in summarizing my question. You can see below what return values I am getting on the right.

value = $(e.target).text()              # value => 'target text'
value.charAt(0)                           # =>*nothing at all!*  

value = "manually assigned text"          # value => 'manually assigned text'
value.charAt(0)                           # =>* 'm'

Here's my snippet for further inspection: https://gist.github.com/4215344

Upvotes: 2

Views: 852

Answers (3)

digitalpixelpro
digitalpixelpro

Reputation: 139

Turns out that inspecting value.length was the key. It was something like 36 characters for some reason. I tried in my haml template to call .strip on the variable there, but the extra whitespace wasn't coming from the ruby side.

I just ended up using jQuery's .trim() function.

Here's my new assignment:

fontName = $(e.target).text().trim()

Upvotes: 0

nbrooks
nbrooks

Reputation: 18233

The problem is not .text(), it's your selector; 'e.target' is not a valid selector. You probably meant to do:

value = $(e.target).text();

As is, calling .text() on an empty object returns blank.

By removing the quotes, you are actually referencing the target property of the event object, which corresponds to an element directly. What you had before was a selector string for <e> elements with class='target', which is obviously not what you want.

Upvotes: 1

dfsq
dfsq

Reputation: 193291

Try this instead:

value = $(e.target).text();

no quotes around e.target.

Upvotes: 3

Related Questions