David
David

Reputation: 17

Add TOGGLE to "show div when text is entered"

The user is able to see options appear beneath a input field when they start typing. This is the Javascript that currently does this:

    #number {
    display:none;
    }
    
    <body onload="
    $('#gname').bind('keyup change',function(){
    if(this.value.length > 0){
    $('#number').show();
    }
    else {
    $('#number').hide();}
    });
    ">

    <input type="text" id="gname">

    <div id="number">
        testing testing
    </div>
</body>

I'm trying to also give a user the option to toggle on the div before they type as well, and also to toggle off the div once it's appeared after typing...

Any ideas on how to manipulate the code?

Upvotes: 0

Views: 1438

Answers (2)

Zoltan Toth
Zoltan Toth

Reputation: 47687

Use the toggle() function - DEMO

$(function() {

    $('#gname').on('keyup change', function() {
        if (this.value.length > 0) {
            $('#number').show();
        } else {
            $('#number').hide();
        }
    });    

    $("#hint").on("click", function() {
        $('#number').toggle();
    });

});

UPDATE

To disable the hint to re-appear after it was disable by the button click - simply unbind the event listeners from it:

$("#hint").on("click", function() {
    $('#number').toggle();
    $('#gname').off('keyup change');
});

DEMO

Upvotes: 3

Sushanth --
Sushanth --

Reputation: 55750

You want to handle the focus and blur functions for it.. Try this

$('#gname').bind('keyup change blur', function() {
    if (this.value.length > 0) {
        $('#number').show();
    }
    else {
        $('#number').hide();
    }
});

$('#gname').on('focus', function() {
    $('#number').show();

});​

Check DEMO

Upvotes: 0

Related Questions