I want to create a form field where multiple data can be inserted using "add" button and after pressing "ok or submit" all the data from the form is posted.
After pressing "add" the data is pushed into an array callded formData.values . However, when I press the "add" button, the behavior is erratic.
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]
I want the values pushed like:
1st trial --- form.data.values should be [a]
2nd --- should be [a,b]
3rd --- should be [a,b,c]
This is my jQuery code: You can also see it in 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));
try something like this
formData.show();
$( this).unbind( "click" );//just add this line
Reason : Because you are binding click everytime you are hovering. so once you click button that many click event are fired.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.