我想创建一个表单字段,可以使用&#34添加多个数据;添加"按下"确定或提交"表格中的所有数据都已过帐。
按下"添加"数据被推送到一个调用formData.values的数组中。但是,当我按下"添加"按钮,行为不稳定。
Its output on console is like:
1st trial -- typing "a" and pressing add button... formData.values = [a]
2nd trial -- typing "b" and pressing add button... formData.values = [a, a, b]
3rd trial -- typing "c" and pressing add button... formData.values = [a, a, b, a, b, c]
我希望推送的值如下:
1st trial --- form.data.values should be [a]
2nd --- should be [a,b]
3rd --- should be [a,b,c]
这是我的jQuery代码:你也可以在jsfiddle here
中看到它(function($){
$.fn.multiData = function( options ){
var $this = this;
var id; // id of add button
var defaults = {
addMoreButton : true,
addCancelButton : true
};
var settings = $.extend( {}, defaults, options );
var formData;
var addButton;
this.on('focusin', ':input', function(){
var $inputName = $(this);
id = $inputName.data( 'more' );
addButton = $(id);
addButton.show();
// getting value from <input name="value">
formData.name = $inputName.attr('name');
console.log(formData.name + ' formData.name' );
});
this.on('focusout', ':input', function(){
//id = $(this).data( 'more' );
//id = '#' + id;
var focussedBox = $(this);
var textBoxData = $.trim( $(this).val() );
if( textBoxData === '' ){
addButton.hide();//$(id).hide();
}
else{
addButton.on( 'click', function( event ){
event.preventDefault();
// **THESE 3 LINES** IS WHERE I WANT HELP
console.log( 'initial ' + textBoxData );
formData.values.push( textBoxData );
console.log( 'ln 37 testBoxData=' + textBoxData + ' formData.values=' + formData.values + ' ' + formData.values.length);
$(this).hide();//$(id).hide(); or addButton.hide() but later wont work dont know why.
focussedBox.val(''); // clearing the field after adding data.
formData.show();
});
}
});
formData = {
name: null,
values: [],
show: function(){
$('#result').html( this.values );
}
};
console.log( settings );
return this; // to enable chaining
};
// form-div is used multiple times so storing it for quick response
var formDiv = $('#form-div');
formDiv.removeClass('no-js');
// checking if javascript is on or not. If off disabled = true
var disabled = formDiv.hasClass('no-js');
if( !disabled ){
formDiv.multiData();
}
else {
alert( 'javascript is disabled' );
}
}(jQuery));
答案 0 :(得分:2)
尝试这样的事情
formData.show();
$( this).unbind( "click" );//just add this line
原因:因为您每次悬停时都是绑定点击。所以一旦你点击按钮就会触发很多点击事件。
<强> DEMO 强>