3

When I run this function:

onUnCheck: function(el) {
var thenames = "icon-"+el.find("label:first").text().replace(/ /g,'').toLowerCase();        
alert(thenames);            
$("'."+thenames+"'").hide("fast");
}

I generate a string. I can see in the alert() that it is indeed the correct string. Example:

icon-jira

But when I pass the string in as a jQuery selector it does not work.

I know the function's logic is sound because pasting in the result of my alert() makes it work.

Why won't jQuery accept my string?

2 Answers 2

5
$('.'+thenames).hide("fast");

This will look for ".icon-jira." You were looking for "'.icon-jira'" which adds the quotes to the selector.

Sign up to request clarification or add additional context in comments.

Comments

4

It looks like you have an extra set of single quotes (''). Try this:

onUnCheck: function(el) {
  var thenames = "icon-"+el.find("label:first").text().replace(/\s/g,'').toLowerCase();        
  alert(thenames);            
  $("."+thenames).hide("fast");
}

Also, consider using /\s/g instead of / /g -- /\s/g is a little less error prone and a bit more readable.

2 Comments

Thanks for that extra tip. If I may ask one more silly question: What if I wanted to strip out: periods, commas, (), /,\, and _ how would I add that to this replace?
To get remove of those character specifically you can use .replace(/[.,()/\\_]/g, ""). Note that inside a regex character set only ^, -, ], and ` \ ` have to be escaped. Another option is get remove characters that are not alphanumeric. In that case you can use .replace(/[^\a-zA-Z0-9]/g, ""), though keep in mind that this regex also removes accented characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.