0

I have a weird problem. I have a freight calculation field to be executed if the User deletes a digit input , I hide one content. While running the script in chrome console, it is loaded, but when using the call in html, js it does not run. This is what I have.

https://jsfiddle.net/diasbass/u3xr0921/

jQuery(document).ready(function($) {
    $("#btnFreteSimulacao").click(function() {
        $("#txtCep").keyup(function() {
            if ($("#txtCep").val()) {
                $('p.montagem').hide();
            } else {
                $('p.montagem').show();
            }
        });
    });
});
3
  • 1
    You have to click the button to enabled the keyup handler on the input. Is this intentional? What's the desired behavior? Commented Jun 9, 2016 at 14:40
  • 1
    working fine in jsfiddle. just remember to include jQuery. Anyway, you shouldn't bind a keyup event every time the user clicks the button. Commented Jun 9, 2016 at 14:41
  • 1
    This appears to be working just fine. In what way is it not working for you? I go to your jsFiddle, click the button, and then enter/remove keystrokes in the input. The content hides/shows accordingly. What's the problem? Commented Jun 9, 2016 at 14:43

2 Answers 2

1

The keyup event handler is inside the click function, probably it is of no use.

Also need to check $("#txtCep").val().length for showing and hiding the p.montagem

jQuery(document).ready(function($) {

            $("#txtCep").keyup(function() {         
                if($("#txtCep").val().length ==0) {
                    $('p.montagem').hide();             
                } else {
                    $('p.montagem').show();
                }
            });     

    });

jsfiddle

Sign up to request clarification or add additional context in comments.

2 Comments

An empty string also evaluates to false in JavaScript.
Thank you ! I had not realized it . Now it worked properly.
1

Here you are mixing two asynchronous events 1) Button click 2) Input keyup. Your code expects to work when both are happening same time. I would suggest remove dependency on one event. Like below.

    $( "#btnFreteSimulacao" ).click(function() {                
       // $("#txtCep").keyup(function() {         
            if($("#txtCep").val()) {
                $('p.montagem').hide();             
            } else {
                $('p.montagem').show();
            }
        });     
   // });
    });

If thats not possible, try to look towards promises.

1 Comment

Thank you ! I had not realized it . Now it worked properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.