我想创建一个表单字段,可以使用“添加”按钮在其中插入多个数据,并在按下“确定或提交”后发布表单中的所有数据。
按下“添加”后,数据被推送到一个名为 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));
最佳答案
尝试这样的事情
formData.show();
$( this).unbind( "click" );//just add this line
原因:因为每次悬停时都会绑定(bind)点击。所以一旦你点击按钮,就会触发许多点击事件。
关于javascript - 为什么不需要的数据被推送到我的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23842116/