My JS :
$("#modalADDpp").on('shown',function(e){
$(this).find('input[type=text]').filter(':first').focus();
var count = 0;
alert(count);
$('#pp_tab a').click(function () {
$(this).tab('show');
})
$("#TenPP").typing({ // jquery for check when finish typing
start: function(event ,$elem) {
$(".add-on").remove();
return false;
},
stop: function (event, $elem) {
count ++;
alert(count);
if(count == 1 )
{
Ajax_Check_Name($elem);// Check name same with database by ajax
}
return false;
},
delay: 500
});
$("#modalADDpp").on('hidden',function(e){
$(this).closest('form').find("input[type=text], textarea").val("");
$(".add-on").remove();
});
});
I crate $count = 0 at my modal shown . At first time , it work ok . But when hide modal and re-open , $count not = 0 , $count now = 2 => my function will call two time and if close agains , it plus to 3 , 4 ,5 times .
I use
if(count == 1 )
because i want it run only one time .So it work ok but I dont know where is problem . Need Help !!!
Code of typing.js
(function ($) {
//--------------------
// jQuery extension
//--------------------
$.fn.typing = function (options) {
return this.each(function (i, elem) {
listenToTyping(elem, options);
});
};
//-------------------
// actual function
//-------------------
function listenToTyping(elem, options) {
// override default settings
var settings = $.extend({
start: null,
stop: null,
delay: 400
}, options);
// create other function-scope variables
var $elem = $(elem),
typing = false,
delayedCallback;
// start typing
function startTyping(event) {
if (!typing) {
// set flag and run callback
typing = true;
if (settings.start) {
settings.start(event, $elem);
}
}
}
// stop typing
function stopTyping(event, delay) {
if (typing) {
// discard previous delayed callback and create new one
clearTimeout(delayedCallback);
delayedCallback = setTimeout(function () {
// set flag and run callback
typing = false;
if (settings.stop) {
settings.stop(event, $elem);
}
}, delay >= 0 ? delay : settings.delay);
}
}
// listen to regular keypresses
$elem.keypress(startTyping);
// listen to backspace and delete presses
$elem.keydown(function (event) {
if (event.keyCode === 8 || event.keyCode === 46) {
startTyping(event);
}
});
// listen to keyups
//$elem.keyup(stopTyping);
// listen to blurs
$elem.blur(function (event) {
stopTyping(event, 0);
});
}
})(jQuery);
try to reset the count to 0 ... on hidden or in stop function ...
if(count == 1 )
{
Ajax_Check_Name($elem);// Check name same with database by ajax
count = 0;
}
Or
$("#modalADDpp").on('hidden',function(e){
$(this).closest('form').find("input[type=text], textarea").val("");
$(".add-on").remove();
count = 0;
});
Related
I use tinyMCE 5 in my web site to enter data stored in a database. Therefore I need to limit the entered size, including format information, to the size of the data field. How can I prohibit the user to enter more then the allowed number of bytes, say 2000?
Best of all if I could add some information like "42/2000" on the status bar.
We had a similar requirement in our project (difference: the output should be <entered_chars>/<chars_left> instead of <entered_chars>/<max_chars>), and it ended up being a custom plugin, based on the wordcount plugin. There is some hacks in there, which could make it fail whenever tinyMCE changes, since there is no API for the statusbar in version 5 at this point of time.
But maybe you will still find it useful:
(function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var maxChars = function (editor) {
return editor.getParam('number_max_chars', 3600);
};
var applyMaxChars = function (editor) {
return editor.getParam('restrict_to_max_chars', true);
};
var Settings = {
maxChars: maxChars,
applyMaxChars: applyMaxChars
};
var global$1 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker');
var getText = function (node, schema) {
var blockElements = schema.getBlockElements();
var shortEndedElements = schema.getShortEndedElements();
var isNewline = function (node) {
return blockElements[node.nodeName] || shortEndedElements[node.nodeName];
};
var textBlocks = [];
var txt = '';
var treeWalker = new global$1(node, node);
while (node = treeWalker.next()) {
if (node.nodeType === 3) {
txt += node.data;
} else if (isNewline(node) && txt.length) {
textBlocks.push(txt);
txt = '';
}
}
if (txt.length) {
textBlocks.push(txt);
}
return textBlocks;
};
var strLen = function (str) {
return str.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, '_').length;
};
var countCharacters = function (node, schema) {
var text = getText(node, schema).join('');
return strLen(text);
};
var createBodyCounter = function (editor, count) {
return function () {
return count(editor.getBody(), editor.schema);
};
};
var createMaxCount = function (editor) {
return function () {
return Settings.maxChars(editor);
}
}
var createRestrictToMaxCount = function (editor) {
return function () {
return Settings.applyMaxChars(editor);
}
}
var get = function (editor) {
return {
getCount: createBodyCounter(editor, countCharacters),
getMaxCount: createMaxCount(editor),
getRestrictToMaxCount: createRestrictToMaxCount(editor)
};
};
var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
function isAllowedKeycode(event) {
// allow arrow keys, backspace and delete
const key = event.keyCode;
return key === 37 || key === 38 || key === 39 || key === 40 || key === 8
|| key === 46;
}
var updateCount = function (editor, api) {
editor.getContainer().getElementsByClassName(
'tox-statusbar__text-container')[0].textContent = String(
api.getCount()) + " / " + String(
Settings.maxChars(editor) - api.getCount());
};
var setup = function (editor, api, delay) {
var debouncedUpdate = global$2.debounce(function () {
return updateCount(editor, api);
}, delay);
editor.on('init', function () {
updateCount(editor, api);
global$2.setEditorTimeout(editor, function () {
editor.on('SetContent BeforeAddUndo Undo Redo keyup', debouncedUpdate);
editor.on('SetContent BeforeAddUndo Undo Redo keydown', function (e) {
if (!isAllowedKeycode(e) && Settings.applyMaxChars(editor) &&
api.getCount() >= Settings.maxChars(editor)) {
e.preventDefault();
e.stopPropagation();
}
});
}, 0);
});
};
function Plugin(delay) {
if (delay === void 0) {
delay = 300;
}
global.add('charactercount', function (editor) {
var api = get(editor);
setup(editor, api, delay);
return api;
});
}
Plugin();
}());
Currently I'm working on a preprocessor for the paste plugin, so that the max_length effects also pasted text. That's why you see the charactercount API in the code.
I'm looking for a way to insert a checkbox into a select and fetch each column individually, all using DataTables. I found an excellent example in https://jsfiddle.net/Lxytynm3/2/ but for some reason, when selecting all records, filtering does not display the data as expected. Would anyone have a solution to work properly?
Thanks in advance.
The link application code is as follows:
$(document).ready(function() {
function cbDropdown(column) {
return $('<ul>', {
'class': 'cb-dropdown'
}).appendTo($('<div>', {
'class': 'cb-dropdown-wrap'
}).appendTo(column));
}
$('#example').DataTable({
initComplete: function() {
this.api().columns().every(function() {
var column = this;
var ddmenu = cbDropdown($(column.header()))
// -------------------------------------------------------
.on('change', ':checkbox', function() {
var active;
var vals = $(':checked', ddmenu).map(function(index, element) {
active = true;
return $.fn.dataTable.util.escapeRegex($(element).val());
}).toArray().join('|');
column
.search(vals.length > 0 ? '^(' + vals + ')$' : '', true, false)
.draw();
// -------------------------------------------------------
// Highlight the current item if selected.
if (this.checked) {
$(this).closest('li').addClass('active');
// If 'Select all / none' clicked ON
if ($(this).val() === "1") {
$(ddmenu).find('input[type="checkbox"]').prop('checked', this.checked)
//$(".cb-dropdown li").prop('checked', true);
//$('.cb-dropdown').closest('li').find('input[type="checkbox"]').prop('checked', true);
// $('this input[type="checkbox"]').prop('checked', true); works!
// $( 'input[type="checkbox"]' ).prop('checked', this.checked);
// $(this).find('input[type="checkbox"]').prop('checked', this.checked)
//$('div.cb-dropdown-wrap.active').children().find('input[type="checkbox"]').prop('checked', this.checked)
}
} else // 'Select all / none' clicked OFF
{
$(this).closest('li').removeClass('active');
// test if select none
if ($(this).val() === "1") {
// code to untick all
$(ddmenu).find('input[type="checkbox"]').prop('checked', false)
}
}
// Highlight the current filter if selected.
var active2 = ddmenu.parent().is('.active');
if (active && !active2) {
ddmenu.parent().addClass('active');
// Change Container title to "Filter on" and green
//$(this).parent().find('.cb-dropdown li:nth-child(n+1)').css('color','red');
$('active2 li label:contains("Filter OFF")').text('Yeees');
} else if (!active && active2) {
ddmenu.parent().removeClass('active');
}
});
// -------------------------------------------------------
var mytopcount = '0'; // Counter that ensures only 1 entry per container
// loop to assign all options in container filter
column.data().unique().sort().each(function(d, j) {
// Label
var $label = $('<label>'),
$text = $('<span>', {
text: d
}),
// Checkbox
$cb = $('<input>', {
type: 'checkbox',
value: d
});
$text.appendTo($label);
$cb.appendTo($label);
ddmenu.append($('<li>').append($label));
// -----------------
// Add 'Select all / none' to each dropdown container
if (mytopcount == '0') // Counter that ensures only 1 entry per container
{
$label = $('<label>'), $text = $('<span>', {
text: "Select all / none"
}),
$cb = $('<input>', {
type: 'checkbox',
value: 1
});
$text.prependTo($label).css('margin-bottom', '6px');
$cb.prependTo($label);
ddmenu.prepend($('<li>').prepend($label).css({
'border-bottom': '1px solid grey',
'margin-bottom': '6px'
}));
mytopcount = '1' // This stops this section running again in cotainer
}
});
});
}
});
});
It seems as though the issue was with the select all checkbox. One solution would be to check for "1" within the vals initialisation, this seems to work:
var vals = $(':checked', ddmenu).map(function(index, element) {
if($(element).val() !== "1"){
return $.fn.dataTable.util.escapeRegex($(element).val());
}
}).toArray().join('|');
That should see you with some results upon the top checkbox being checked. Hope that helps.
I create a setInterval method like below, I want to stop it anytime from anywhere. By the way, that function is in a if-else statement, so I cannot access the stop function.
How can it be possible?
var intervalID = setInterval(function () {
if (flag) {
stopTimer();
Pages.Page1.Label1.text = "";
}
if (time == 0) {
stopTimer();
Pages.Page1.Label1.text = "";
Device.makeCall(callNumber.rows[0][0]);
} else
updateTime();
}, 1000);
function updateTime() {
time = time - 1;
Pages.Page1.Label1.text = time;
}
function stopTimer() {
clearInterval(intervalID);
}
Just set the flag variable to true.
flag = true;
Alternatively, i would suggest to declare your functions outside of the if / else scope .
For instance, create a timer instance with start / stop methods as such :
timer = function() {};
timer.prototype.start = function ()
{
this.timerId = setInterval(function () {
/* ... */
/* call to doWork here or simply your code */
}, 1000);
}
timer.prototype.doWork = function ()
{
// override here if you want and wall doWork in setInterval
}
timer.prototype.stop = function ()
{
clearInterval(this.timerId);
}
var t = new timer();
// start the timer
t.start();
// stop the timer
t.stop();
This way you can handle your timer as you want.
I have successfully setup a multiselect box which dynamically populates from my 'multiselect_json.php' file. (multiselect plugin from here : https://github.com/nicholasryan/jquery_jeditable/commit/1055cf6d51100d241b1e089c8cabcbad26207320)
My problem is that I can only return 1 value pair that is marked as 'selected'
example:
My dropdown options are as follows:
1-product1
2-product2
3-product3
array('selected') = 1; works and correctly highlights this option
but does not work when I specify 2 selected options
array('selected') = 1;
array('selected') = 2;
in this case the last 'selected' value (2) is used and the previous 'selected' value (1) is ignored.
This means that if there are many pre-selected items on a particular multiselect list, then it is difficult for the user to remember what was previously selected and has to go back and re-select what was previously selected manually.
Does anyone know how I can pass multiple 'selected' value pairs for my multiselect box using the jeditable plugin?
jquery.jeditable.js
(function($) {
$.fn.editable = function(target, options) {
if ('disable' == target) {
$(this).data('disabled.editable', true);
return;
}
if ('enable' == target) {
$(this).data('disabled.editable', false);
return;
}
if ('destroy' == target) {
$(this)
.unbind($(this).data('event.editable'))
.removeData('disabled.editable')
.removeData('event.editable');
return;
}
var settings = $.extend({}, $.fn.editable.defaults, {target:target}, options);
/* setup some functions */
var plugin = $.editable.types[settings.type].plugin || function() { };
var submit = $.editable.types[settings.type].submit || function() { };
var buttons = $.editable.types[settings.type].buttons
|| $.editable.types['defaults'].buttons;
var content = $.editable.types[settings.type].content
|| $.editable.types['defaults'].content;
var element = $.editable.types[settings.type].element
|| $.editable.types['defaults'].element;
var reset = $.editable.types[settings.type].reset
|| $.editable.types['defaults'].reset;
var callback = settings.callback || function() { };
var onedit = settings.onedit || function() { };
var onsubmit = settings.onsubmit || function() { };
var onreset = settings.onreset || function() { };
var onerror = settings.onerror || reset;
/* Show tooltip. */
if (settings.tooltip) {
$(this).attr('title', settings.tooltip);
}
settings.autowidth = 'auto' == settings.width;
settings.autoheight = 'auto' == settings.height;
return this.each(function() {
/* Save this to self because this changes when scope changes. */
var self = this;
/* Inlined block elements lose their width and height after first edit. */
/* Save them for later use as workaround. */
var savedwidth = $(self).width();
var savedheight = $(self).height();
/* Save so it can be later used by $.editable('destroy') */
$(this).data('event.editable', settings.event);
/* If element is empty add something clickable (if requested) */
if (!$.trim($(this).html())) {
$(this).html(settings.placeholder);
}
$(this).bind(settings.event, function(e) {
/* Abort if element is disabled. */
if (true === $(this).data('disabled.editable')) {
return;
}
/* Prevent throwing an exeption if edit field is clicked again. */
if (self.editing) {
return;
}
/* Abort if onedit hook returns false. */
if (false === onedit.apply(this, [settings, self])) {
return;
}
/* Prevent default action and bubbling. */
e.preventDefault();
e.stopPropagation();
/* Remove tooltip. */
if (settings.tooltip) {
$(self).removeAttr('title');
}
/* Figure out how wide and tall we are, saved width and height. */
/* Workaround for http://dev.jquery.com/ticket/2190 */
if (0 == $(self).width()) {
settings.width = savedwidth;
settings.height = savedheight;
} else {
if (settings.width != 'none') {
settings.width =
settings.autowidth ? $(self).width() : settings.width;
}
if (settings.height != 'none') {
settings.height =
settings.autoheight ? $(self).height() : settings.height;
}
}
/* Remove placeholder text, replace is here because of IE. */
if ($(this).html().toLowerCase().replace(/(;|"|\/)/g, '') ==
settings.placeholder.toLowerCase().replace(/(;|"|\/)/g, '')) {
$(this).html('');
}
self.editing = true;
self.revert = $(self).html();
$(self).html('');
/* Create the form object. */
var form = $('<form />');
/* Apply css or style or both. */
if (settings.cssclass) {
if ('inherit' == settings.cssclass) {
form.attr('class', $(self).attr('class'));
} else {
form.attr('class', settings.cssclass);
}
}
if (settings.style) {
if ('inherit' == settings.style) {
form.attr('style', $(self).attr('style'));
/* IE needs the second line or display wont be inherited. */
form.css('display', $(self).css('display'));
} else {
form.attr('style', settings.style);
}
}
/* Add main input element to form and store it in input. */
var input = element.apply(form, [settings, self]);
/* Set input content via POST, GET, given data or existing value. */
var input_content;
if (settings.loadurl) {
var t = setTimeout(function() {
input.disabled = true;
content.apply(form, [settings.loadtext, settings, self]);
}, 100);
var loaddata = {};
loaddata[settings.id] = self.id;
if ($.isFunction(settings.loaddata)) {
$.extend(loaddata, settings.loaddata.apply(self, [self.revert, settings]));
} else {
$.extend(loaddata, settings.loaddata);
}
$.ajax({
type : settings.loadtype,
url : settings.loadurl,
data : loaddata,
async : false,
success: function(result) {
window.clearTimeout(t);
input_content = result;
input.disabled = false;
}
});
} else if (settings.data) {
input_content = settings.data;
if ($.isFunction(settings.data)) {
input_content = settings.data.apply(self, [self.revert, settings]);
}
} else {
input_content = self.revert;
}
content.apply(form, [input_content, settings, self]);
input.attr('name', settings.name);
/* Add buttons to the form. */
buttons.apply(form, [settings, self]);
/* Add created form to self. */
$(self).append(form);
/* Attach 3rd party plugin if requested. */
plugin.apply(form, [settings, self]);
/* Focus to first visible form element. */
$(':input:visible:enabled:first', form).focus();
/* Highlight input contents when requested. */
if (settings.select) {
input.select();
}
/* discard changes if pressing esc */
input.keydown(function(e) {
if (e.keyCode == 27) {
e.preventDefault();
reset.apply(form, [settings, self]);
}
});
/* Discard, submit or nothing with changes when clicking outside. */
/* Do nothing is usable when navigating with tab. */
var t;
if ('cancel' == settings.onblur) {
input.blur(function(e) {
/* Prevent canceling if submit was clicked. */
t = setTimeout(function() {
reset.apply(form, [settings, self]);
}, 500);
});
} else if ('submit' == settings.onblur) {
input.blur(function(e) {
/* Prevent double submit if submit was clicked. */
t = setTimeout(function() {
form.submit();
}, 200);
});
} else if ($.isFunction(settings.onblur)) {
input.blur(function(e) {
settings.onblur.apply(self, [input.val(), settings]);
});
} else {
input.blur(function(e) {
/* TODO: maybe something here */
});
}
form.submit(function(e) {
if (t) {
clearTimeout(t);
}
/* Do no submit. */
e.preventDefault();
/* Call before submit hook. */
/* If it returns false abort submitting. */
if (false !== onsubmit.apply(form, [settings, self])) {
/* Custom inputs call before submit hook. */
/* If it returns false abort submitting. */
if (false !== submit.apply(form, [settings, self])) {
/* Check if given target is function */
if ($.isFunction(settings.target)) {
var str = settings.target.apply(self, [input.val(), settings]);
$(self).html(str);
self.editing = false;
callback.apply(self, [self.innerHTML, settings]);
/* TODO: this is not dry */
if (!$.trim($(self).html())) {
$(self).html(settings.placeholder);
}
} else {
/* Add edited content and id of edited element to POST. */
var submitdata = {};
submitdata[settings.name] = input.val();
submitdata[settings.id] = self.id;
/* Add extra data to be POST:ed. */
if ($.isFunction(settings.submitdata)) {
$.extend(submitdata, settings.submitdata.apply(self, [self.revert, settings]));
} else {
$.extend(submitdata, settings.submitdata);
}
/* Quick and dirty PUT support. */
if ('PUT' == settings.method) {
submitdata['_method'] = 'put';
}
/* Show the saving indicator. */
$(self).html(settings.indicator);
/* Defaults for ajaxoptions. */
var ajaxoptions = {
type : 'POST',
data : submitdata,
dataType: 'html',
url : settings.target,
success : function(result, status) {
if (ajaxoptions.dataType == 'html') {
$(self).html(result);
}
self.editing = false;
callback.apply(self, [result, settings]);
if (!$.trim($(self).html())) {
$(self).html(settings.placeholder);
}
},
error : function(xhr, status, error) {
onerror.apply(form, [settings, self, xhr]);
}
};
/* Override with what is given in settings.ajaxoptions. */
$.extend(ajaxoptions, settings.ajaxoptions);
$.ajax(ajaxoptions);
}
}
}
/* Show tooltip again. */
$(self).attr('title', settings.tooltip);
return false;
});
});
/* Privileged methods */
this.reset = function(form) {
/* Prevent calling reset twice when blurring. */
if (this.editing) {
/* Before reset hook, if it returns false abort reseting. */
if (false !== onreset.apply(form, [settings, self])) {
$(self).html(self.revert);
self.editing = false;
if (!$.trim($(self).html())) {
$(self).html(settings.placeholder);
}
/* Show tooltip again. */
if (settings.tooltip) {
$(self).attr('title', settings.tooltip);
}
}
}
};
});
};
$.editable = {
types: {
defaults: {
element : function(settings, original) {
var input = $('<input type="hidden"></input>');
$(this).append(input);
return(input);
},
content : function(string, settings, original) {
$(':input:first', this).val(string);
},
reset : function(settings, original) {
original.reset(this);
},
buttons : function(settings, original) {
var form = this;
if (settings.submit) {
/* If given html string use that. */
if (settings.submit.match(/>$/)) {
var submit = $(settings.submit).click(function() {
if (submit.attr("type") != "submit") {
form.submit();
}
});
/* Otherwise use button with given string as text. */
} else {
var submit = $('<button type="submit" />');
submit.html(settings.submit);
}
$(this).append(submit);
}
if (settings.cancel) {
/* If given html string use that. */
if (settings.cancel.match(/>$/)) {
var cancel = $(settings.cancel);
/* otherwise use button with given string as text */
} else {
var cancel = $('<button type="cancel" />');
cancel.html(settings.cancel);
}
$(this).append(cancel);
$(cancel).click(function(event) {
if ($.isFunction($.editable.types[settings.type].reset)) {
var reset = $.editable.types[settings.type].reset;
} else {
var reset = $.editable.types['defaults'].reset;
}
reset.apply(form, [settings, original]);
return false;
});
}
}
},
text: {
element : function(settings, original) {
var input = $('<input />');
if (settings.width != 'none') { input.attr('width', settings.width); }
if (settings.height != 'none') { input.attr('height', settings.height); }
/* https://bugzilla.mozilla.org/show_bug.cgi?id=236791 */
//input[0].setAttribute('autocomplete','off');
input.attr('autocomplete','off');
$(this).append(input);
return(input);
}
},
textarea: {
element : function(settings, original) {
var textarea = $('<textarea />');
if (settings.rows) {
textarea.attr('rows', settings.rows);
} else if (settings.height != "none") {
textarea.height(settings.height);
}
if (settings.cols) {
textarea.attr('cols', settings.cols);
} else if (settings.width != "none") {
textarea.width(settings.width);
}
$(this).append(textarea);
return(textarea);
}
},
select: {
element : function(settings, original) {
var select = $('<select />');
$(this).append(select);
return(select);
},
content : function(data, settings, original) {
/* If it is string assume it is json. */
if (String == data.constructor) {
eval ('var json = ' + data);
} else {
/* Otherwise assume it is a hash already. */
var json = data;
}
for (var key in json) {
if (!json.hasOwnProperty(key)) {
continue;
}
if ('selected' == key) {
continue;
}
var option = $('<option />').val(key).append(json[key]);
$('select', this).append(option);
}
/* Loop option again to set selected. IE needed this... */
$('select', this).children().each(function() {
if ($(this).val() == json['selected'] ||
$(this).text() == $.trim(original.revert)) {
$(this).attr('selected', 'selected');
}
});
/* Submit on change if no submit button defined. */
if (!settings.submit) {
var form = this;
$('select', this).change(function() {
form.submit();
});
}
}
},
selectmulti: {
element : function(settings, original) {
var select = $('<select />');
$(this).append(select);
$(this).find('select').attr('multiple','multiple');
return(select);
},
content : function(data, settings, original) {
/* If it is string assume it is json. */
if (String == data.constructor) {
eval ('var json = ' + data);
} else {
/* Otherwise assume it is a hash already. */
var json = data;
}
for (var key in json) {
if (!json.hasOwnProperty(key)) {
continue;
}
if ('selected' == key) {
continue;
}
var option = $('<option />').val(key).append(json[key]);
$('select', this).append(option);
}
/* Loop option again to set selected. IE needed this... */
$('select', this).children().each(function() {
if ($(this).val() == json['selected'] ||
$(this).text() == $.trim(original.revert)) {
$(this).attr('selected', 'selected');
}
});
}
}
},
/* Add new input type */
addInputType: function(name, input) {
$.editable.types[name] = input;
}
};
/* Publicly accessible defaults. */
$.fn.editable.defaults = {
name : 'value',
id : 'id',
type : 'text',
width : 'auto',
height : 'auto',
event : 'click.editable',
onblur : 'cancel',
loadtype : 'GET',
loadtext : 'Loading...',
placeholder: 'Click to edit',
loaddata : {},
submitdata : {},
ajaxoptions: {}
};
})(jQuery);
multiselect_json.php
<?php
$projectid = $_POST['id'];
$inputvalue = $_POST['value'];
require_once('connect.php');
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$array = explode ( '_' , $projectid ) ; // This will split $inputvalue by the character '_'
$column = $array[0];
$id = $array[1];
// get full list of products
$query = "SELECT DISTINCT * FROM products ORDER BY productname";
$result = mysqli_query($mysqli, $query);
// get selected productid's
$query2 = "SELECT DISTINCT productid FROM projectsproducts WHERE projectid='$id'";
$result2 = mysqli_query($mysqli, $query2);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$id_1 = $row['id'];
$productname = $row['productname'];
$array[$id_1] = $productname;
};
$array['selected'] = '2';
$array['selected'] = '3';
print json_encode($array);
?>
When I write in my mongoDB with mongoose the operation is treated with success, my document is saved, but there is also all kind of weird other sutff written down. It seems to be mongoose code. What could cause this?
I add stuff in a specific array with:
resultReference.ref[arrayLocation].allEvents.push(theEvent);
{id: 11, allEvents: [] } is the structure of a ref element, and I push theEvent in the allEvents array. I then resultReference.save()
I use express, mongoose and mongoHQ for database. I tried on a local mongo server, and this annoyance is still there. I've print in my console the document to write before save() and non of this weird code is there.
{
id 11
allEvents
[
0
{
_events
{
maxListeners 0
}
_doc
{
_id {"$oid": "4eb87834f54944e263000003"}
title "Test"
allDay false
start 2011-11-10 13:00:00 UTC
end 2011-11-10 15:00:00 UTC
url "/test/4eb87834f54944e263000002"
color "#99CCFF"
ref "4eb87834f54944e263000002"
}
_activePaths
{
paths
{
title "modify"
allDay "modify"
start "modify"
end "modify"
url "modify"
color "modify"
ref "modify"
}
states
{
init
{ }
modify
{
title true
allDay true
start true
end true
url true
color true
ref true
}
require
{ }
}
stateNames
[
0 "require"
1 "modify"
2 "init"
]
}
_saveError null
_validationError null
isNew true
_pres
{
save
[
0
function (next) {
// we keep the error semaphore to make sure we don't
// call `save` unnecessarily (we only need 1 error)
var subdocs = 0
, error = false
, self = this;
var arrays = this._activePaths
.map('init', 'modify', function (i) {
return self.getValue(i);
})
.filter(function (val) {
return (val && val instanceof DocumentArray && val.length);
});
if (!arrays.length)
return next();
arrays.forEach(function (array) {
subdocs += array.length;
array.forEach(function (value) {
if (!error)
value.save(function (err) {
if (!error) {
if (err) {
error = true;
next(err);
} else
--subdocs || next();
}
});
});
});
}
1 "function checkForExistingErrors(next) {
if (self._saveError){
next(self._saveError);
self._saveError = null;
} else {
next();
}
}"
2 "function validation(next) {
return self.validate.call(self, next);
}"
]
}
_posts
{
save
[ ]
}
save
function () {
var self = this
, hookArgs // arguments eventually passed to the hook - are mutable
, lastArg = arguments[arguments.length-1]
, pres = this._pres[name]
, posts = this._posts[name]
, _total = pres.length
, _current = -1
, _asyncsLeft = proto[name].numAsyncPres
, _next = function () {
if (arguments[0] instanceof Error) {
return handleError(arguments[0]);
}
var _args = Array.prototype.slice.call(arguments)
, currPre
, preArgs;
if (_args.length && !(arguments[0] === null && typeof lastArg === 'function'))
hookArgs = _args;
if (++_current < _total) {
currPre = pres[_current]
if (currPre.isAsync && currPre.length < 2)
throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)");
if (currPre.length < 1)
throw new Error("Your pre must have a next argument -- e.g., function (next, ...)");
preArgs = (currPre.isAsync
? [once(_next), once(_asyncsDone)]
: [once(_next)]).concat(hookArgs);
return currPre.apply(self, preArgs);
} else if (!proto[name].numAsyncPres) {
return _done.apply(self, hookArgs);
}
}
, _done = function () {
var args_ = Array.prototype.slice.call(arguments)
, ret, total_, current_, next_, done_, postArgs;
if (_current === _total) {
ret = fn.apply(self, args_);
total_ = posts.length;
current_ = -1;
next_ = function () {
if (arguments[0] instanceof Error) {
return handleError(arguments[0]);
}
var args_ = Array.prototype.slice.call(arguments, 1)
, currPost
, postArgs;
if (args_.length) hookArgs = args_;
if (++current_ < total_) {
currPost = posts[current_]
if (currPost.length < 1)
throw new Error("Your post must have a next argument -- e.g., function (next, ...)");
postArgs = [once(next_)].concat(hookArgs);
return currPost.apply(self, postArgs);
}
};
if (total_) return next_();
return ret;
}
};
if (_asyncsLeft) {
function _asyncsDone (err) {
if (err && err instanceof Error) {
return handleError(err);
}
--_asyncsLeft || _done.apply(self, hookArgs);
}
}
function handleError (err) {
if ('function' == typeof lastArg)
return lastArg(err);
if (errorCb) return errorCb.call(self, err);
throw err;
}
return _next.apply(this, arguments);
}
errors null
}
]
}
]
The reason this happened is because I didnt save my schema in mongoose in the proper order. This would mean declaring your child schema before a parent to get proper behavior.