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

2019-08-26 14:30发布

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"); }
});

标签: jquery forms
3条回答
forever°为你锁心
2楼-- · 2019-08-26 14:49

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!

查看更多
虎瘦雄心在
3楼-- · 2019-08-26 14:53

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');
});
查看更多
老娘就宠你
4楼-- · 2019-08-26 15:12

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"); }
});
查看更多
登录 后发表回答