简体   繁体   中英

How to show/hide div when a value is assigned to an input

I am trying to automatically show a div when a value is assigned to a input element.

So far i am using keyup function, but this works only if i typed in a value. How can i show/hide a div if the value is assigned to the input without me typing it in?

Here is what i have.

<script>
$("#ven_id").keyup(function(){
if($(this).val()) {
    $(".inv_item").slideDown(500);
} else {
    $(".inv_item").slideUp(500);
}

});
</script>

any suggestions?

Consider using the change handler. jQuery Documentation

$("#ven_id").change(function(event) {
    if(event.target.value) {
        $(".inv_item").slideDown(500);
    } else {
        $(".inv_item").slideUp(500);
    }
});

Example Fiddle

The problem you are seeing is that an event isn't fired when the input's value is set in code. This answers your question I believe .val() doesn't trigger .change() in jquery .

After the popup sets the input's value you need to manually trigger the event.

$("#ven_id").val("somevalue").trigger("keyup");

Try this one, May it can help You.

if($(this).val().length > 0) {
    $(".inv_item").slideDown(500);
} else {
    $(".inv_item").slideUp(500);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM