views:

65

answers:

3

I'm trying to alter the code below so that if "this" contains the class "search_init", it will only replace that class, as the markup itself has multiple classes applied to it. I tried ~= and ^=, but that gives me errors about missing ().

$("tfoot input").focus( function () {
            if ( this.className == "search_init" )  {
                this.className = "";
                this.value = "";
            }
        } );
+1  A: 
$("tfoot input.search_init").focus( function () {
                $(this).removeClass("search_init");
                this.value = "";
            }
        } );

~= "Selects elements that have the specified attribute with a value containing a given word, delimited by spaces." This would work, but it makes much more sense to use built in class selectors than mess with the class attribute itself. Likewise with ^=, which "Selects elements that have the specified attribute with a value beginning exactly with a given string."

CrazyJugglerDrummer
+5  A: 

Try this out:

$("tfoot input").focus( function () {
    var $this = $(this);
    if ( $this.hasClass("search_init") )  {
        $this.removeClass("search_int").val('');
    }
});
PetersenDidIt
Short, efficient, readable. +1
Willi
+1, though you could make it even shorter with `$(this).filter('. search_init').removeClass('search_init).val('');`
patrick dw
@patrick yes but you with that you could be running the removeClass and val on an empty jQuery object which is a waste.
PetersenDidIt
@petersendidit - Yes, I see your point.
patrick dw
+1  A: 

Should be a one liner:

$('tfoo input.search_init').focus(function(e) {$(this).removeClass('search_init').val('');});

As an aside, you could change the styling with a .search_init:focus css meta-class.