Search code examples
javagwtjsni

how to prompt user to get alert on press back space on focus out


I am trying to prompt user when he loose focus from text field on press back space but my code hav little bugs it also promp user when he press backspace during typing how its happening i an not sure please help me.

t1.addListener(new TextFieldListenerAdapter() {

       public void onFocus(Field field) {  
     System.out.println("onFocus"); 
       } 
       public void onBlur(Field field) {  
         System.out.println("onBlur");
         call();
            }
    });

    RootPanel.get().add(t1);

        }  

 public native void call()/*-{

 //alert("dfv");

    $wnd.onkeypress = GetChar;

     function GetChar (event)
     {
        var key = event.keyCode;

        if(key==8)//checking keyCode of key for backspace

                {
         var x= window.confirm("Are you sureyou want to leave the page");

        if (x==true)
                 {
              alert(window.history.back())

                  }
           else if(x==false)
         {

          return false;
         }
            }
    }                   

}-*/;


Solution

  • Try this one

        import com.google.gwt.event.dom.client.KeyCodes;
        import com.google.gwt.i18n.client.DateTimeFormat;
        import com.google.gwt.user.client.Event;
        import com.google.gwt.user.client.Event.NativePreviewEvent;
    
        ...
    
    
        Event.addNativePreviewHandler(new Event.NativePreviewHandler() {
    
            @Override
            public void onPreviewNativeEvent(final NativePreviewEvent event) {
                if (event.getTypeInt() == Event.ONKEYPRESS) {
                    if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_BACKSPACE) {
                        System.out.println("Back space is pressed");
                    }
                }
            }
        });
    
        t1.sinkEvents(Event.ONKEYPRESS);