user3681937 user3681937 - 5 months ago 8
Javascript Question

JQuery Fade Hidden Field In And Out On Select Change

I currently have this jquery code that is supposed to show and hide a field based on the content on what is selected:

$('#State').on('change', function() {
var s = $('#State option:selected').text;

if(s !== "")
{
$('#showme').fadeIn();
}
if(s === "")
{
$('#showme').fadeOut();
}

});


Here is a working fiddle: https://jsfiddle.net/b0h6xd0t/

It will fade the field in, but it won't fade it back out for some reason. Any ideas?

Thanks!

Answer

In jQuery, text() is method. Methods, in order to work, require the use of the parentheses as shown below:

var s = $('#State option:selected').text(); // I added: ()

Note: In JavaScript, the empty string is considered false. So for neatness, you can turn your code into the following:

$('#State').on('change', function() {
    var s = $('#State option:selected').text;

    if(s) { // If it's true
        $('#showme').fadeIn();
    }
    else { // If it's false
        $('#showme').fadeOut();
    }
});

Check out an updated version of your fiddle here.

As an alternative, as another answer has also correctly pointed, you can use:

$('#showme').fadeOut(500, function() {
    $(this).text(s).fadeIn(500);
});

Putting s inside text() can also check its status, because according to the documentation s is:

The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation.

In your case, as I pointed above, the empty string is considered false, so it fulfils the requirement.

Note: In this case, $('#showme') will fade out anyway, but if the value is true (not empty) it will fade back in. I'm not sure if you actually want that particular effect, so take a look at this fiddle as well.