当从下拉列表中选择“添加新”时,我会弹出一个模式窗口。用户可以在文本字段中键入要添加到下拉列表的新选项。只要每次在每个新字段中实际输入文本,它就可以正常工作(感谢这个很棒的社区的帮助为什么 jQuery ajax 在这里发布两次? :-) 现在我的问题是,如果用户通过单击关闭模式在它之外,然后选择另一个“添加新”并尝试输入文本,当单击添加按钮时,会有一堆无关的操作,就像上面之前链接的问题一样。显然需要做一些解除绑定,但我无法弄清楚。理想情况下,用户应该能够打开和关闭任意数量的模式窗口,并且仍然能够输入数据。有任何想法吗?
这是jQuery:
<script type="text/javascript">
var Classofentry = '';
$('#upload_form option[value="addnew"]').click(function(){
// Show modal window
$('#add-new').modal('show');
// Get the class
//var Classofentry = $('#upload_form option[class]').attr("class");
var Classofentry = $(this).attr("class");
//console.log(Classofentry);
$('#add-new-submit').on('click', function(){
// Get new option from text field
var value = $('#add-new-text').val();
//console.log(value);
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/change_options",
data: {new_option: value, new_option_class: Classofentry},
dataType: "html",
error: errorHandler,
success: success
});
function success(data)
{
$('#'+Classofentry).append("<option value='" + data + "'selected=\"selected\">" + data + "</option>");
//alert(data);
//alert('Success!');
}
function errorHandler()
{
alert('Error with AJAX!');
}
$('#add-new-submit').unbind('click'); // This fixes the problem for multiple entries
//$('#add-new-text').unbind('click');
//$('#upload_form option[value="addnew"]').unbind('click')
$('#add-new').modal('toggle');
});
//$('#add-new-submit').unbind('click');
//$('#upload_form option[value="addnew"]').unbind('click');
});
</script>
这是模态:
<!-- add-new field -->
<div class="modal small hide fade" id="add-new" tabindex="-1" role="dialog" aria-labelledby="add-new-fieldLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="add-new-fieldLabel">Add New Field</h3>
</div>
<div class="modal-body">
<p>Would you like to add a new item?</p>
<input type="text" id="add-new-text" name="add-new-text" placeholder="Type the new option">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="add-new-submit" name="add-new-submit"/>Add</button>
</div>
</div><!-- /add-new field -->