how to disable background-color input fields - forms

I am using a form validation with javascript.
When submitting, the background-color of those input fields which are not valid changes to red color. When filling up this field and typing into another input field, the red background-color of the former field should go away. This is at the moment not the case. It only disappears when submitting again. How can I make this possible that the bg color changes back to normal when typing into another field?
// Return true if the input value is not empty
function isNotEmpty(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = (inputValue.length !== 0); // boolean
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
/* If "isValid" is false, print the errorMsg; else, reset to normal display.
* The errorMsg shall be displayed on errorElement if it exists;
* otherwise via an alert().
*/
function showMessage(isValid, inputElement, errorMsg, errorElement) {
if (!isValid) {
// Put up error message on errorElement or via alert()
if (errorElement !== null) {
errorElement.innerHTML = errorMsg;
} else {
alert(errorMsg);
}
// Change "class" of inputElement, so that CSS displays differently
if (inputElement !== null) {
inputElement.className = "error";
inputElement.focus();
}
} else {
// Reset to normal display
if (errorElement !== null) {
errorElement.innerHTML = "";
}
if (inputElement !== null) {
inputElement.className = "";
}
}
}
The form:
<td>Name<span class="red">*</span></td>
<td><input type="text" id="name" name="firstname"/></td>
<p id="nameError" class="red"> </p>
The submit:
<input type="submit" value="SEND" id="submit"/>
Css:
input.error { /* for the error input text fields */
background-color: #fbc0c0;
}
Update:
I tried this but it seems not to work:
function checkFilled() {
var inputVal = document.querySelectorAll("#offerteFirstname, #offerteLastname, #offertePhone, #offertePoster, #offerteStreet").value;
if (inputVal == "") {
document.querySelectorAll("#offerteFirstname, #offerteLastname, #offertePhone, #offertePoster, #offerteStreet").style.backgroundColor = "red";
}
else{
document.querySelectorAll("#offerteFirstname, #offerteLastname, #offertePhone, #offertePoster, #offerteStreet").style.backgroundColor = "white";
}
}
checkFilled();

here example of it
<input type="text" id="subEmail" onchange="checkFilled();"/>
and now you can JavaScript on input
function checkFilled() {
var inputVal = document.getElementById("subEmail").value;
if (inputVal == "") {
document.getElementById("subEmail").style.backgroundColor = "white";
}
else{
document.getElementById("subEmail").style.backgroundColor = "red";
}
}
checkFilled();
here working demo

Try
$(formElement).on('keyup','input.error', function(){
if(<values changed>){
$(this).removeClass('error');
}
});

Related

Salesforce lightning input's element.set not working anymore after summer 18 release

I am using below snippet to check for valid phone number format and then trying to set the formatted value to the current input element. But after summer 18 release I'm unable to set input with new formatted value.
TestApp
<aura:application extends="force:slds">
<lightning:input type="text" label="Num" aura:id="ele" onchange="
{!c.changeNum}" />
</aura:application>
Controller:
({
changeNum : function(component, event, helper) {
helper.changeNum(component, event);
}
})
Helper:
({
changeNum : function(component, event) {
var element = event.getSource();
var phonenumber = element.get("v.value");
if(phonenumber){
var updatedValue = phonenumber.replace(/-/g, "");
if(/^\d{10}$/.test(updatedValue)){
phonenumber = updatedValue.match(new RegExp('\\d{4}$|\\d{3}', 'g')).join("-");
}
else{
var x = phonenumber.replace(/[^0-9._-]/g, "").replace(/ +/, " ");
phonenumber = x;
if(!/^[0-9-]+$/.test(phonenumber.slice(-1))){
phonenumber = phonenumber.slice(0, -1);
}
}
}
console.log(phonenumber);
element.set('v.value', phonenumber);
}
})
element.set is not able to update the formatted value. The lightning input element is still able to accept alphabets.
We can solve the issue by using Promise
({
handleInputChange : function(component, event) {
try {
var element = event.getSource();
var inputValue = element.get("v.value");
var formattedValue;
var chkPattern = new Promise(
function (resolve, reject) {
if (inputValue) {
formattedValue = inputValue.replace(/[^0-9-]/g, "").replace(/ +/, " ");
resolve(formattedValue); // fulfilled
} else {
var reason = new Error('kitten is not happy');
reject(reason); // reject
}
}
);
chkPattern.then(function (fulfilled) {
element.set('v.value', fulfilled);
}).catch(function (error) {
console.log(error.message);
});
} catch(e) {
this.consoleLog(e.stack, true)
}
}
})

How to filter with multiple condition text input in Ag-Grid?

Using ag-grid-enterprise v5.4.0
create multiple textFilter input ex: [CONTAINS] filterText AND [NOT CONTAIN] filterText2 just like Excel data analysis
but both filterType2 and filterText are undefined after click [APPLY FILTER]
https://embed.plnkr.co/4nAjGKmChqJiRcqz6E2n/
I believe what you are trying to do would be best achieved with the Filter Component. This allows you full control of the filter pain, whether you are in enterprise or not. Here are the required methods for each custom filter:
function CustomFilter() {}
CustomFilter.prototype.init = function (params) {
//Put any initial functions you need here (such as setting values to null)
};
CustomFilter.prototype.getGui = function () {
//return a string of HTML or a DOM element/node
};
CustomFilter.prototype.doesFilterPass = function (params) {
//Logic for your custom Filter
//return True if the row should display, false otherwise
};
CustomFilter.prototype.isFilterActive = function () {
//logic for displaying the filter icon in the header
};
CustomFilter.prototype.getModel = function() {
//store the filter state
};
CustomFilter.prototype.setModel = function(model) {
//restore the filter state here
};
Here is an example of how to implement an "Includes x but Excludes y" filter:
function DoubleFilter() {
}
DoubleFilter.prototype.init = function (params) {
this.valueGetter = params.valueGetter;
this.filterText = null;
this.setupGui(params);
};
// not called by ag-Grid, just for us to help setup
DoubleFilter.prototype.setupGui = function (params) {
this.gui = document.createElement('div');
this.gui.innerHTML =
'<div style="padding: 4px; width: 200px;">' +
'<div style="font-weight: bold;">Custom Athlete Filter</div>' +
'Include: <div><input style="margin: 4px 0px 4px 0px;" type="text" id="includesText" placeholder="Includes..."/></div>' +
'Exclude: <div><input style="margin: 4px 0px 4px 0px;" type="text" id="excludesText" placeholder="Excludes..."/></div>' +
'</div>';
// add listeners to both text fields
this.eIncludesText = this.gui.querySelector('#includesText');
this.eIncludesText.addEventListener("changed", listener);
this.eIncludesText.addEventListener("paste", listener);
this.eIncludesText.addEventListener("input", listener);
// IE doesn't fire changed for special keys (eg delete, backspace), so need to
// listen for this further ones
this.eIncludesText.addEventListener("keydown", listener);
this.eIncludesText.addEventListener("keyup", listener);
this.eExcludesText = this.gui.querySelector('#excludesText');
this.eExcludesText.addEventListener("changed", listener2);
this.eExcludesText.addEventListener("paste", listener2);
this.eExcludesText.addEventListener("input", listener2);
// IE doesn't fire changed for special keys (eg delete, backspace), so need to
// listen for this further ones
this.eExcludesText.addEventListener("keydown", listener2);
this.eExcludesText.addEventListener("keyup", listener2);
var that = this;
function listener(event) {
that.includesText = event.target.value;
params.filterChangedCallback();
}
function listener2(event) {
that.excludesText = event.target.value;
params.filterChangedCallback();
}
};
DoubleFilter.prototype.getGui = function () {
return this.gui;
};
DoubleFilter.prototype.doesFilterPass = function (params) {
var passed = true;
var valueGetter = this.valueGetter;
var include = this.includesText;
var exclude = this.excludesText;
var value = valueGetter(params).toString().toLowerCase();
return value.indexOf(include) >= 0 && (value.indexOf(exclude) < 0 || exclude == '') ;
};
DoubleFilter.prototype.isFilterActive = function () {
return (this.includesText !== null && this.includesText !== undefined && this.includesText !== '')
|| (this.excludesText !== null && this.excludesText !== undefined && this.excludesText !== '');
};
DoubleFilter.prototype.getModel = function() {
var model = {
includes: this.includesText.value,
excludes: this.excludesText.value
};
return model;
};
DoubleFilter.prototype.setModel = function(model) {
this.eIncludesText.value = model.includes;
this.eExcludesText.value = model.excludes;
};
Here is a modified plunker. I placed the filter just on the Athlete column, but the DoubleFilter can be applied to any column once it is created.
EDIT:
I realized you were asking for a rather generic double filter in your question with "Includes and Excludes" as an example. Here is a plunker that has a more generic double filter.
ag-Grid now supports this behavior, by default, in version 18.0.0.
https://www.ag-grid.com/ag-grid-changelog/?fixVersion=18.0.0

reactive forms: use one validator for multiple fields

I'm using angular 2 reactive forms and made a validator for a date of birth field. The validator is working, but it turns out the date of birth field is split into three new field: year, month, day. They all have their own validators. My question is, how can I change my code so my original date of birth validator works on three fields.
my original validator that checks one field.
input(2000/12/12) is valid
export function dobValidator(control) {
const val = control.value;
const dobPattern = /^\d{4}\/\d{2}\/\d{2}$/ ;
const comp = val.split('/');
const y = parseInt(comp[0], 10);
const m = parseInt(comp[1], 10);
const d = parseInt(comp[2], 10);
const jsMonth = m - 1;
const date = new Date(y, jsMonth, d);
const isStringValid = dobPattern.test(control.value);
const isDateValid = (date.getFullYear() === y && date.getMonth() === jsMonth && date.getDate() === d);
return (isStringValid && isDateValid) ? null : { invalidDob: ('Date of birth not valid') };
};
new html with 3 fields
year has a validator that checks the year
day has a validator that checks if the input is between 1 and 31
month has a validator that checks if the input is between 1 and 12.
I want to combine the above input of the three field into a new string and use my original date of birth validator.
<label>Date of birth :</label>
<div>
<div class="col-xs-1">
<input required type="text" formControlName="day" class="form-control" placeholder="dd" id="day"/>
<p *ngIf="form.controls.day.dirty && form.controls.day.errors">{{ form.controls.day.errors.invalidDay }}</p>
</div>
<div class="col-xs-1">
<input required type="text" formControlName="month" class="form-control" placeholder="mm" id="month"/>
<p *ngIf="form.controls.month.dirty && form.controls.month.errors">{{ form.controls.month.errors.invalidMonth }}</p>
</div>
<div class="col-xs-2">
<input required type="text" formControlName="year" class="form-control" placeholder="yyyy" id="year"/>
<p *ngIf="form.controls.year.dirty && form.controls.year.errors">{{ form.controls.year.errors.invalidYear }}</p>
</div>
</div>
<div>
<button type="submit" [disabled]="form.invalid">Submit</button>
</di>
I have created a validator for comparing two dates (their format is NgbDateStruct - as used in ng-bootstrap package's datepickers)
import { Directive, forwardRef, Attribute } from '#angular/core';
import { Validator, AbstractControl, NG_VALIDATORS, ValidatorFn } from '#angular/forms';
import { NgbDateStruct } from "#ng-bootstrap/ng-bootstrap";
import { toDate } from "../helpers/toDate";
export function dateCompareValidator(compareToControl: string, compareToValue: NgbDateStruct, compareType: string, reverse: boolean, errorName: string = 'dateCompare'): ValidatorFn {
return (c: AbstractControl): { [key: string]: any } => {
let compare = function (self: Date, compareTo: Date): any {
console.log('comparing ', compareType.toLowerCase());
console.log(self);
console.log(compareTo);
if (compareType.toLowerCase() === 'ge') {
if (self >= compareTo) {
return true;
} else {
return false;
}
} else if (compareType.toLowerCase() === 'le') {
if (self <= compareTo) {
return true;
} else {
return false;
}
}
return false;
};
// self value
let v = c.value;
// compare vlaue
let compareValue: Date;
let e;
if (compareToValue) {
compareValue = toDate(compareToValue);
} else {
e = c.root.get(compareToControl);
if (e) {
compareValue = toDate(e.value);
}
else {
// OTHER CONTROL NOT FOUND YET
return null;
}
}
let controlToValidate: AbstractControl = reverse ? e : c;
// validate and set result
let error = null;
let result = compare(toDate(c.value), compareValue);
if (result === true) {
console.log('clearing errors', compareToControl);
if (controlToValidate.errors) {
delete controlToValidate.errors[errorName];
if (!Object.keys(controlToValidate.errors).length) {
controlToValidate.setErrors(null);
}
}
else {
console.log('errors property not found in control', controlToValidate);
}
} else {
error = {};
error[errorName] = false;
controlToValidate.setErrors(error);
console.log(controlToValidate.errors);
console.log(controlToValidate.value);
console.log('Error Control', controlToValidate);
console.log('returning errors');
}
return reverse ? null : error;
}
}
Couldn't manage to modify much lot to best describe here as an answer but I believe you would get your query answered in this validator function code.
Note:
Function toDate() used in the code is a small function I created to convert NgbDateStruct into a javascript date object so that comparing dates can get easier. Here goes its implementation:
import { NgbDateStruct } from "#ng-bootstrap/ng-bootstrap"
export function toDate(ngbDate: NgbDateStruct): Date {
return ngbDate != null ? new Date(Date.UTC(ngbDate.year, ngbDate.month, ngbDate.day)) : null;
}

Start search after 2 character typed in Chosen drop down

In Chosen drop down plugin, a search is started after 2 characters are typed in chosen drop down.
I need the search to not start until after inputing at least two characters in the search box.
Can any one suggest how to do this?
I did a small change to start to search after the third character, is not the best option but works, in the chosen JS in the AbstractChosen.prototype.winnow_results function after the line searchText = this.get_search_text(); add the following code: if (searchText != "" && searchText.length < 3) return;. Remember to change the < 3 by your own size.
Hope this help you
See part of the code below:
AbstractChosen.prototype.winnow_results = function() {
var escapedSearchText, option, regex, regexAnchor, results, results_group, searchText, startpos, text, zregex, _i, _len, _ref;
this.no_results_clear();
results = 0;
searchText = this.get_search_text();
if (searchText != "" && searchText.length < 3) return;
escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
I know this post it's old but i had to face this problem just now and wanted to share my result. I wrapped everything in a function extendedSearch and set it as a callback while chosen is emitting the chosen:showing_dropdown event.
My problem was that i need the search to show the results after the 2nd character typed in search and must filter out certain strings from the results.
Bellow you'll find a demo which shows results on the 3rd character typed in, and will keep visible only those results that end with letter "E".
$(function() {
/**
* By default the results are hidden when clicking a dropdown.
* {
* toggleResults: false, // a function(searchValue) that returns a boolean
* filterResults: false, // a function(dropDownValue, selectValue) that returns a boolean
* }
* #param options
*/
const extendedSearch = (options = {}) => {
const defaultOptions = {
toggleResults: false,
filterResults: false,
};
options = { ...{},
...defaultOptions,
...options
};
/**
* Main element
*/
return (evt, params) => {
let originalElement = $(evt.currentTarget);
let searchInput = params.chosen.search_field;
const customSearch = (options = {}) => {
let defaultOptions = {
originalElement: null,
searchInput: null
};
options = { ...{},
...defaultOptions,
...options
};
if (!(options.originalElement instanceof jQuery) || !options.originalElement) {
throw new Error('Custom Search: originalElement is invalid.');
}
if (!(options.searchInput instanceof jQuery) || !options.searchInput) {
throw new Error('Custom Search: searchInput is invalid.');
}
let res = options.searchInput
.parent()
.next('.chosen-results');
res.hide();
if (typeof options.toggleResults !== 'function') {
options.toggleResults = (value) => true;
}
if (options.filterResults && typeof options.filterResults !== 'function') {
options.filterResults = (shownText = '', selectValue = '') => true;
}
/**
* Search Input Element
*/
return (e) => {
let elem = $(e.currentTarget);
let value = elem.val() || '';
if (value.length && options.toggleResults(value) === true) {
res.show();
if (options.filterResults) {
let children = res.children();
let active = 0;
$.each(children, (idx, item) => {
let elItem = $(item);
let elemIdx = elItem.attr('data-option-array-index');
let shownText = elItem.text();
let selectValue = options.originalElement.find('option:eq(' + elemIdx + ')').attr('value') || '';
if (options.filterResults(shownText, selectValue) === true) {
active++;
elItem.show();
} else {
active--;
elItem.hide();
}
});
if (active >= 0) {
res.show();
} else {
res.hide();
}
}
} else {
res.hide();
}
};
};
options = {
...{},
...options,
...{
originalElement,
searchInput
}
};
let searchInstance = customSearch(options);
searchInput
.off('keyup', searchInstance)
.on('keyup', searchInstance)
}
};
/** This is the final code */
const inputValidator = (value) => {
console.log('input', value);
return $.trim(value).length > 2;
};
const textResultsValidator = (dropDownValue, selectValue) => {
if ($.trim(dropDownValue).substr(-1, 1) === 'E') {
console.log('results shown', dropDownValue, '|', selectValue);
return true;
}
return false;
};
$(".chosen-select")
.chosen()
.on('chosen:showing_dropdown', extendedSearch({
toggleResults: inputValidator,
filterResults: textResultsValidator
}));
});
#import url("https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
<select class="chosen-select">
<option value="">Pick something</option>
<option value="APPLE">APPLE</option>
<option value="APPLE JUICE">APPLE JUICE</option>
<option value="BANANA">BANANA</option>
<option value="ANANAS">ANANAS</option>
<option value="ORANGE">ORANGE</option>
<option value="ORANGES">ORANGES</option>
<option value="STRAWBERRY">STRAYBERRY</option>
</select>

Jeditable > Multiple select > Can't return multiple 'selected' values

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);
?>