0
$\begingroup$

I am trying to get a separate div (a custom 'continue' button) to appear when the user starts typing into a text input.
I am currently using this:

var submitButton = $('#submitButton');
submitButton.hide();
submitButton.on("showSubmitButton", function(event) {
    $( this ).show();
    $( this ).css('opacity', '0');
    $( this ).fadeTo(400, 0.6);
});
var textInput = $('#textInput');
textInput.click(function() {
    $( this ).find('input:text').val(''); // this clears the default 'type your name here' text 
});
textInput.keyDown(function() {
    submitButton.trigger("showSubmitButton");
});

When I had the "showSubmitButton" line inside the textInput.click function the submit button appeared on the click, but I want the button only to appear when the user has typed something into the input.
I have also used .keyPress(), but both key events trigger a 'has no method' error. I assume I must be using them incorrectly, but I don't know how.

$\endgroup$
1
  • $\begingroup$ TIP, line 4,5,6 why not chain it instead of typing $(this) 3 times?like show().css().fadeTo() $\endgroup$ Commented Oct 29, 2013 at 15:58

2 Answers 2

1
$\begingroup$

The shorthand functions for event handlers aren't camel case, so it's .keydown(), .keypress(), etc. rather than .keyDown() or .keyPress(). That said, I'd use either the input or keypress events (depending on browser support), with a check to see if the value of the textbox isn't an empty string:

textInput.find('input:text').on('input', function(e) {
    if($.trim(this.value).length > 0) {
        submitButton.trigger('showSubmitButton');
    }
    else {
        // consider hiding the submit button?
    }
});
$\endgroup$
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I've just realised (just after I posted this question, or course!) that there's no camel-case in the keydown event. So it was the capital D that was throwing it out. It works now. Thanks for the answer too - I may give that alternative a go.
Thanks - your alternative works nicely. I changed the 'length > 0' to 'length < 2' so that it only triggers on the first input (it will also trigger when the user deletes down to 1 character-length, but I can live with that).
1
$\begingroup$

It is not keyDown - it is keydown

$\endgroup$

Comments

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.