Caelan Grgurovic Caelan Grgurovic - 4 months ago 10
HTML Question

jquery not adding class when inputs are not empty

I am creating a simple function which shows a login button when both inputs are not empty, however, jQuery does not seem to want to allow me.

I have checked to make sure the jQuery API that I am using is up to date and correct, but nothing seems to be out of the ordinary.

jQuery:

$(document).ready(function(){
var u = $.trim($("#_jq-loC1").val());
var p = $.trim($('#_jq-loC2').val());
var l = $('#_jq-slO1');

if(u.length > 0 && p.length > 0) {
l.addClass('slO1');
} else {
l.removeClass('slO1');
}
});


HTML:

<input type="text" name="username" id="_jq-loC1" placeholder="Username" autocomplete="off">
<input type="password" name="password" id="_jq-loC2" placeholder="Password" autocomplete="off">
<input style="width: 0.1px; height:0.1px; opacity: 0; overflow: hidden;" id="login" type="submit" value="">
<div class="send-login-container">
<label class="send-login" id="_jq-slO1" for="login"></label>
</div>


CSS:

.slO1{
width: 54px;
}


Cheers.

Answer

That's because your code is only executed on the page load. So if you change the content of your inputs later, nothing will be executed.

You need to watch changes in your inputs.

In your $(document).ready() you can replace your code by :

var toggleSubmit = function () {
    var u = $.trim($("#_jq-loC1").val());
    var p = $.trim($('#_jq-loC2').val());
    var l = $('#_jq-slO1');

    if(u.length > 0 && p.length > 0) {
        l.addClass('slO1');
    } else {
        l.removeClass('slO1');
    }
};

$('#_jq-loC1').on('change', function () {
    toggleSubmit();
});

$('#_jq-loC2').on('change', function () {
    toggleSubmit();
});

// Check on page load
toggleSubmit();
Comments