简体   繁体   中英

Clicking ok on javascript Alert submits form

I have an alert that display to the user if they add an element that already exists on the page. I have an autocomplete and if the item the user chooses I alert them that the element has already been added. However when I click the ok of the alert, it submits the form which I don't want. This only happens for a specific case. It happens when I press enter on the autocomplete element, if the element exists, I give an alert. Then if I click ok on the alert the form submits! I have code to prevent enter submitting the form. Here is my code:

$(window).keydown(function(event){
    if(event.keyCode == 13) {
        event.preventDefault();
        return false;
    }
});

$(".autocomp_centers").autocomplete({

    serviceUrl:'/suggest_centers',
        maxHeight:400,
        width:252,
        params: {country: $("#country").val() },
        minChars:2,
        onSelect: function(value, data){
            var ids = [];
            $("#sister-centers-list > li").each(function(index, value){
                ids.push($(value).attr('class'));
            });

            if ($.inArray("center-"+data, ids)  == -1){
                $("#hidden-ids").append('<input type="hidden" name="center_ids[]" value="' + data +'" class="center-' + data + '"/>');
                $('#sister-centers-list').append('<li class="center-' + data + '">' + value + ' <a href="#sister-center" class="remove-center-before-save" id="' + data + '">Remove</a></li>');
            }else{
                alert("Sister center has already been added.");
            }               
            $("#sister-search").val("");
        }
});

This is the rails form:

    <%= form_for @center, :url => center_update_sister_centers_path(@center) do |f| %>

        <div class="field" style="margin-top:10px;">
            <%= f.submit 'Save', :class => "btn purple-button" %>
        </div>

How come the form is being submitted when it shouldn't and how do I stop this from happening? Thanks

如果您不希望表单提交,除非您已经使用jQuery,否则请在表单中添加.submit()处理函数。

It's a matter of which element is focussed. You have to put your keydown event on the input field in question. Or you add a submit() handler to your form and react accordingly.

Preventing it in the window is way too late, because it already triggered the submit when focus was on the form element (and only after that bubbles up to the window object).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM