Search code examples
javascriptjquerykeypress

If keycode && input are not empty do something


I have barcode input in which I enter barcodes multiple times, every time I add barcode, barcode is added to the list even if I only press enter with empty value.

I want to start function only if user press enter key == 13 and value is not empty.

This is code:

if(key == 13) {}

I tried but without success:

var value = $("#barcode").val();
if(key == 13 && value.length > 0)
{alert("This works!")}...

Solution

  • You need to run your code under either the keyup or keypress event. Assuming you use jQuery to attach the event, you should also use the which property of the provided event object to get the keycode. Try this:

    $('#barcode').keypress(function(e) {
        if (e.which == 13 && this.value) {
            alert("This works!")
        }
    })
    

    Working example