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"); }
});
You can use
attr
andremoveAttr
too.The error was, you were missing
()
infront ofval
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!
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 :
Thanks to @Novocaine88 and @Anthony-Grist for the answer
$(this).val
should be either$(this).val()
ORthis.value
JS (Updated)