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