Reputation: 14747
This code represents a html markup where the user can add one or more phones to her/his profile. So, I use backbone to add text fields where the user can specify them.
<form method="post" class="form-horizontal" action="..">
<!-- Here I have another text input controls -->
<!-- START: backbone view -->
<div id="phones">
<div class="phones-container">
<!-- New phone template [label, text input] -->
</div>
<!-- Add phone template button -->
<button id="btn-add-phone">Add another phone</button>
</div>
<!-- END: backbone view -->
</form>
The phone template looks like this:
<div class="form-group tpl-phone">
<label class="">Other:</label>
<div class="col-sm-8 col-lg-7 controls">
<input value="" type="tel" class="reference" name="reference[]" >
</div>
</div>
In backbone I have a function that add a new phone template to the view.
Notice that... the backbone view is just a portion of the form.
var PhoneEditorView = Backbone.View.extend({
el: '#phones',
events: {
"click #btn-add-phone": "onAddPhoneTemplate",
"keyup .reference": "onTypingReference"
},
initialize: function (options) {
_.bindAll(this, 'onAddPhoneTemplate', 'onTypingReference', 'render');
this.model = new PhoneEditor(options);
this.render();
},
onAddPhoneTemplate: function(event){
event && event.preventDefault(); //prevents submit form
console.log('onAddPhoneTemplate()');
var $template = $('.tpl-phone').clone().removeClass('tpl-phone');
$('.phones-container').append($template);
},
onTypingReference: function(event){
event && event.preventDefault();
if(event.which == 13){
console.log('enter key');
}
},
render: function(){
}
});
What is the problem? If the user press Enter key at any text field whaterver if it is inside or outside of view's scope, for some reason onAddPhoneTemplate()
function is called again and another phone's template is added to the view.
The expected behavior on enter key is do nothing, console's output:
enter key
However, after pressing enter key I get at console:
onAddPhoneTemplate()
enter key
Upvotes: 0
Views: 411
Reputation: 171689
Change your button to type=button
.
By default a button is type=submit
unless otherwise specified so when placed in a form it will trigger the form to submit.
When a type=submit
exists in form, hitting enter
will also trigger the form submit
<button type="button" id="btn-add-phone">Add another phone</button>
Upvotes: 2