Search code examples
javascriptjquerydom-eventskeypress

Javascript event keypress


A form has a input field which would contain text values . There is a Save button as well for the form .

Requrement: The save button should get disabled as soon as Input field goes empty.

Problem: Javascript events like change,blur ,focus etc require loss of focus(that is a click outside) ,Hence save button would not get disabled simultaneously the input goes blank without user clicking outside of the field.

The closest being 'keypress' event .However the problem with this is,as soon as I try to make the field empty it checks for the input value and since it already has some value the condition check I have put to disalbe the button fails.

Refer the code below I've used STUDY_NAME is the input field id SAVE_DRAFT_TAB_GENERAL is the save button id.

Code :

    if($(STUDY_NAME)){
        $(STUDY_NAME).addEvent("keypress", function(){
            if($(STUDY_NAME).value == ''){
                $(SAVE_DRAFT_TAB_GENERAL).disabled = true;
            }else {
                $(SAVE_DRAFT_TAB_GENERAL).disabled = false;
            }
        });
    }

Solution

  • You can try using KeyUp event which happens after the user types his values