Reputation: 1316
I have very simple form with lil bit of jQuery inside. What I want to do is to show text input IF I choose specific option in my select field. In that input I want to be able to add new option to my select field. It works fine unless I try to use it multiple times. At the first time it's ok. At 2nd time it adds me additional option field with empty value and label. At 3rd time it adds TWO empty option fields. And so on...
I'm trying to figure out why the hell it happens. Here's code preview and demo: http://jsfiddle.net/rx5orekb/ HTML:
<form action="#" class="source">
<select id="source">
<option value="none">None</option>
<option value="source-xyz">Source XYZ</option>
<option value="something-else">Something Else</option>
<option value="add-new">Add New Source</option>
</select>
<input type="text" placeholder="Type name and hit enter" value="" style="display: none" />
</form>
JS:
var Form = {
addNewSource: function(form, select, newSource) {
select.hide();
newSource.show().focus();
form.on('submit', function(event) {
event.preventDefault();
var label = newSource.val(),
html = '<option value="'+label+'">'+label+'</option>';
select.show().find('option[value=add-new]').before(html);
select.val(label);
newSource.hide().val('');
});
return false;
},
sourceAppendix: function() {
var select = $('.source').find('select');
select.on('change', function() {
var v = $(this).val(),
form = $(this).parents('.source'),
newSource = form.find('input');
if(v == 'add-new') {
Form.addNewSource(form, $(this), newSource);
}
});
}
}
$(document).ready(function() {
Form.sourceAppendix();
});
Thanks a lot!
Upvotes: 0
Views: 480
Reputation: 782693
Every time you call addNewSource()
you bind another submit
handler. So if you call addNewSource
4 times, clicking the submit button will run the submit handler 4 times. And each of these will add another option to the select.
I'm not really sure what you're trying to accomplish by waiting for the submit event before adding the new option to the menu, so I'm not sure how to correct the code. You probably just want to add the new option immediately:
addNewSource: function(form, select, newSource) {
select.hide();
newSource.show().focus();
var label = newSource.val(),
html = '<option value="'+label+'">'+label+'</option>';
select.find('option[value=add-new]').before(html);
},
The .submit()
handler should be bound at top-level, not inside addNewSource
.
Upvotes: 2
Reputation: 8584
See http://jsfiddle.net/rx5orekb/1/
It's happening because every time there's a new change event on the select you're binding to form submit. First time you click on 'add new' you're binding to form submit, 2nd time 'add new' is selected you bind to form submit a 2nd time, so on.
Use
form.unbind('submit');
to unbind the submit on the form.
Upvotes: 1