001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.wicket.ajax;
018
019import org.apache.wicket.Component;
020import org.apache.wicket.ajax.attributes.AjaxCallListener;
021import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
022import org.apache.wicket.markup.html.form.TextField;
023
024/**
025 * <p>
026 *     An Ajax behavior that could be used to prevent the form submit
027 *     when the user presses the <em>ENTER</em> key while in an HTML
028 *     &lt;input type="text" &gt; field.
029 * </p>
030 * <p>
031 *     The behavior could be applied to a {@link TextField} or to a parent
032 *     container that will apply this behavior to all children of type HTMLInputElement.
033 * </p>
034 * <p>
035 *     This Ajax behavior is client-side only, i.e. it never fires an Ajax call to the server.
036 * </p>
037 */
038public class AjaxPreventSubmitBehavior extends AjaxEventBehavior {
039
040        /**
041         * Constructor.
042         */
043        public AjaxPreventSubmitBehavior() {
044                super("keydown");
045        }
046
047        @Override
048        protected void updateAjaxAttributes(final AjaxRequestAttributes attributes) {
049                super.updateAjaxAttributes(attributes);
050
051                Component component = getComponent();
052                if (component instanceof TextField<?> == false)
053                {
054                        attributes.setChildSelector("input");
055                }
056
057                AjaxCallListener listener = new AjaxCallListener();
058                listener.onPrecondition("if (Wicket.Event.keyCode(attrs.event) === 13) {attrs.event.preventDefault();} return false;");
059                attributes.getAjaxCallListeners().add(listener);
060        }
061
062        @Override
063        protected final void onEvent(final AjaxRequestTarget target) {
064                // never called
065        }
066}