Matt W
Matt W

Reputation: 4133

Add class on input (and remove if value hasn't changed)

I've written this simple js to add class to an input on focus, and remove it when it loses focus (if value is empty). However the class doesn't get removed regardless of whether the value is empty or not. Thanks for any help, hugely appreciated

HTML:

<form id="prospects_form" method="post" action="...">
    <input id="form_name" type="text" name="name" placeholder="Name*" />
    <input id="form_email" type="text" name="email" placeholder="Email*" />
    <input id="form_subject" type="text" name="subject" placeholder="Subject*" maxlength="50" />
    <textarea id="form_message" rows="6" cols="5" name="message" placeholder="Message*" maxlength="500"></textarea>

    <button id="form_send" class="btn btn_white" type="submit">Send</button>
</form>

JS:

// When input is focussed
$('#prospects_form > *').focus(function() {
    $(this).addClass("hasText");
});
$('#prospects_form > *').blur(function() {
    if ($(this).val === '') { $(this).removeClass("hasText"); }
});

Upvotes: 0

Views: 2472

Answers (3)

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

You can use attr and removeAttr too.

// When input is focussed
$('#prospects_form > *').focus(function() {
 $(this).attr('class', 'hasText');
});
// blur event..
$('#prospects_form > *').blur(function() {
 if ($(this).val() == '') { 
   $(this).removeAttr('class', 'hasText'); 
 }
});

The error was, you were missing () infront of val in the blur event. Which was the error, and was causing an error and you would have seen that in the Console too.

Here is a fiddle for that too :) http://jsfiddle.net/afzaal_ahmad_zeeshan/kdd84/1/

Good luck!

Upvotes: 0

Stphane
Stphane

Reputation: 3456

val is a method, this is the reason why you have to call it (without parenthesis a reference to the function will be returned)

Focus event not even needed ! Turn the blur handler as :

$('#prospects_form > *').blur(function(e) {
    var $t = $(this);
    $t[($t.val() === '' ? 'removeClass':'addClass')]('hasText');
});

Upvotes: 1

Matt W
Matt W

Reputation: 4133

Thanks to @Novocaine88 and @Anthony-Grist for the answer

$(this).val should be either $(this).val() OR this.value

JS (Updated)

// When input is focussed
$('#prospects_form > *').focus(function() {
    $(this).addClass("hasText");
});
$('#prospects_form > *').blur(function() {
    if (this.value === '') { $(this).removeClass("hasText"); }
});

Upvotes: 0

Related Questions