I want to do autocomplete function for email like this Auto fill email
I have tried this with auto complete email address but failed.
My JS for this code written as follows :
var EmailDomainSuggester = {
domains: ["yahoo.com", "gmail.com", "google.com", "hotmail.com", "me.com", "aol.com", "mac.com", "live.com", "comcast.com", "googlemail.com", "msn.com", "hotmail.co.uk", "yahoo.co.uk", "facebook.com", "verizon.net", "att.net", "gmz.com", "mail.com"],
bindTo: $('#email'),
init: function() {
this.addElements();
this.bindEvents();
},
addElements: function() {
// Create empty datalist
this.datalist = $("<datalist />", {
id: 'email-options'
}).insertAfter(this.bindTo);
// Corelate to input
this.bindTo.attr("list", "email-options");
},
bindEvents: function() {
this.bindTo.on("keyup", this.testValue);
},
testValue: function(event) {
var el = $(this),
value = el.val();
// email has #
// remove != -1 to open earlier
if (value.indexOf("#") != -1) {
value = value.split("#")[0];
EmailDomainSuggester.addDatalist(value);
} else {
// empty list
EmailDomainSuggester.datalist.empty();
}
},
addDatalist: function(value) {
var i, newOptionsString = "";
for (i = 0; i < this.domains.length; i++) {
newOptionsString +=
"<option value='" +
value +
"#" +
this.domains[i] +
"'>";
}
// add new ones
this.datalist.html(newOptionsString);
}
}
EmailDomainSuggester.init();
My HTML code snippet look like below :
<label for="email">Email</label>
<input id="email" name="email" type="email" placeholder="your#email.com">
It doesn't show suggestion when i write.
But it works while i remove character one by one.
IT DOESN'T SHOW SUGGESTIONS WHILE I AM TYPING BUT SHOWS WHEN I REMOVE
CHARACTER ONE BY ONE AFTER '#'
Related
I would like to have two different textboxes, autocomplete the second textbox based on the first textbox results.
For instance, in textbox 1 start typing "un" and all the countries that start with "un" will automatically appear, select united states, in the second textbox start typing "m" and only states within the united states that start with "m" will automatically appear.
My JS files:
var suggest = {
instance : {}, // attached instances
focus : null, // current text field in focus
attach : function (opt) {
// suggest.attach () : attach autosuggest to input field
// opt : options
// - target : ID of target input field, required
// - url : Target URL to fetch suggestions, required
// - delay : Delay before autocomplete fires up, optional, default 500ms
// - min : Minimum characters to fire up autocomplete, default 2
// Create autocomplete wrapper and box
var id = Object.keys(suggest.instance).length,
input = document.getElementById(opt.target);
input.outerHTML = "<div id='acWrap" + id + "' class='acWrap'>" + input.outerHTML + "<div id='acBox" + id + "' class='acBox'></div></div>";
// Set the HTML references and options
suggest.instance[opt.target] = {
input : document.getElementById(opt.target),
wrap : document.getElementById("acWrap" + id),
box : document.getElementById("acBox" + id),
delay : opt.delay ? opt.delay : 500,
url : opt.url,
min : opt.min ? opt.min : 2,
timer : null
};
// Attach key listener
suggest.instance[opt.target].input.addEventListener("keyup", function (evt) {
// Clear old timer
if (suggest.instance[opt.target].timer != null) {
window.clearTimeout(suggest.instance[opt.target].timer);
}
// Hide and clear old suggestion box
suggest.instance[opt.target].box.innerHTML = "";
suggest.instance[opt.target].box.style.display = "none";
// Create new timer, only if minimum characters
if (evt.target.value.length >= suggest.instance[opt.target].min) {
suggest.instance[opt.target].timer = setTimeout(
function () { suggest.fetch(evt.target.id); },
suggest.instance[opt.target].delay
);
}
});
// This is used to hide the suggestion box if the user navigates away
suggest.instance[opt.target].input.addEventListener("focus", function (evt) {
if (suggest.focus != null) { suggest.close(null, true); }
suggest.focus = opt.target;
});
},
fetch : function (id) {
// suggest.fetch() : AJAX get suggestions and draw
// id : ID of target input field, automatically passed in by keyup event
var req = new XMLHttpRequest();
req.addEventListener("load", function () {
var data = JSON.parse(this.response);
if (data.length > 0) {
data.forEach(function (el) {
suggest.instance[id].box.insertAdjacentHTML("beforeend", "<div onclick=\"suggest.select('" + id + "', this);\">" + el + "</div>");
});
suggest.instance[id].box.style.display = "block";
document.addEventListener("click", suggest.close);
}
});
req.open("GET", suggest.instance[id].url + "?term=" + suggest.instance[id].input.value);
req.send();
},
select : function (id, el) {
// suggest.select() : user selects a value from autocomplete
suggest.instance[id].input.value = el.innerHTML;
suggest.instance[id].box.innerHTML = "";
suggest.instance[id].box.style.display = "none";
document.removeEventListener("click", suggest.close);
},
close : function (evt, force) {
// suggest.close() : close the autocomplete box if the user clicks away from the input field
// evt : click event
// force : force close
if (force || event.target.closest(".acWrap") == null) {
suggest.instance[suggest.focus].box.innerHTML = "";
suggest.instance[suggest.focus].box.style.display = "none";
document.removeEventListener("click", suggest.close);
}
}
};
I thought it would simple update the GET term
I created two different js files and updated the term line.
autocompletecountry.js
req.open("GET", suggest.instance[id].url + "?termco=" + suggest.instance[id].input.value);
autocompletestate.js
req.open("GET", suggest.instance[id].url + "?termst=" + suggest.instance[id].input.value);
My search.php files
<?php
// CONNECT TO DATABASE
$host = '11.22.33.44';
$dbname = 'dbname';
$user = 'dbuser';
$password = 'PASSWORD';
$charset = 'utf8';
$pdo = new PDO(
"mysql:host=$host;dbname=$dbname;charset=$charset", $user, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]
);
// SEARCH AND OUTPUT RESULTS
$stmt = $pdo->prepare("select distinct country FROM locationtbl WHERE country LIKE ?");
$stmt->execute(["%" . $_GET['term'] . "%"]);
$data = [];
while ($row = $stmt->fetch(PDO::FETCH_NAMED)) {
$data[] = $row['country'];
}
$pdo = null;
echo json_encode($data);
?>
I created two different search files and updated the term line.
searchcountry.php
$stmt->execute(["%" . $_GET['termco'] . "%"]);
searchstate.php
$stmt->execute(["%" . $_GET['termst'] . "%"]);
Now what is happening is when I start typing in textbox 1 all countries are listed. however when I go to
example.com/searchcountry.php?termco=un
It will only show countries with 'un' in the name.
source: https://code-boxx.com/autocomplete-javascript-php-mysql/
My index.php
<!DOCTYPE html>
<html>
<head>
<link href="autocomplete.css" rel="stylesheet">
<script src="autocompletecountry.js"></script>
<script src="autocompletestate.js"></script>
<script>
/* [INIT - ON WINDOW LOAD] */
window.addEventListener("load", function(){
suggest.attach({
target : "inputA",
url : "http://example.com/searchcountry.php"
});
suggest.attach({
target : "inputB",
url : "http://example.com/searchstate.php",
delay : 200,
min : 3
});
});
</script>
</head>
<body>
<input type="text" id="inputA"/>
<br>
<input type="text" id="inputB"/>
</body>
</html>
Figure out what I had to do.
The page will only work properly with 1 autocomplete.js file
I had to edit the autocomplete.js like below
if (document.getElementById("inputB").value == '' && document.getElementById("inputC").value == '') {
req.open("GET", suggest.instance[id].url + "?term=" + suggest.instance[id].input.value);
req.send();
} else if (document.getElementById("inputC").value == '') {
req.open("GET", suggest.instance[id].url + "?cou=" + document.getElementById("inputA").value + "&term=" + suggest.instance[id].input.value);
req.send();
} else if (document.getElementById("inputA").value != '' && document.getElementById("inputB").value == '') {
req.open("GET", suggest.instance[id].url + "?cou=" + document.getElementById("inputA").value + "&term=" + suggest.instance[id].input.value);
req.send();
} else {
req.open("GET", suggest.instance[id].url + "?cou=" + document.getElementById("inputA").value + "&sta=" + document.getElementById("inputB").value + "&term=" + suggest.instance[id].input.value);
req.send();
}
},
This will allow for 3 autocomplete boxes reliant on the first textbox.
I'm creating a Custom Drop Down Menu using rich combo in CKEDITOR.
I want to add a Search functionality within it like key press search or input textbox search.
My Drop Box looks like this.
Here I don't have any default methods that's why i am doing like this it'wroking fine.
editor.ui.addRichCombo( 'richcombo',{
init : function(){
this.startGroup("");
this.add('search', '<div onmouseover="parent.comboSearch(this);" onclick="parent.nemsComboSearch(this);"><input class="cke_search" placeholder="Search"/></div>', '');
this.add(styles[i].name,styles[i].name,styles[i].element);
},
});
and I am adding combo search here
window.comboSearch= function(element) {
var anchorID = $(element).closest('a').attr("id");
var liDom = $(element).closest('li');
liDom.empty().append('<div id="' + anchorID + '" style="padding:4px 5px;"><input class="cke_search" placeholder="Search" /></div>');
liDom.find('input').off("keyup").on("keyup", function() {
var data = this.value;
//create a jquery object of the rows
var jo = liDom.siblings('li');
data = data.toUpperCase();
var len = jo.length;
for(var i=0;i<len;i++){
if(jo[i].textContent.toUpperCase().indexOf(data)){
jo[i].hidden = true;
}else{
jo[i].hidden = false;
}
}
}).focus(function() {
this.value = "";
$(this).unbind('focus');
});
};
function filter(data, jo) {
if (this.value === "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function(i, v) {
var $t = $(this);
if ($t.is(":icontains('" + data + "')")) {
return true;
}
return false;
}).show();
}
It' working fine.
I'm trying to compare the value of a form element with it's default text (set via the title attribute). If the VALUE == TITLE, change the value to a zero length string. However, I can't seem to make it work. I'm sure it's just my lack of experience with Javascript and jQuery. Many thanks.
HTML
<form name="results-form" id="results-form">
<input type="text" name="price-min" class="form-textbox-small no-radius defaultText" data="Minimum" title="Minimum" onchange="UpdateSearch()">
<input type="text" name="price-max" class="form-textbox-small no-radius defaultText" data="Maximum" title="Maximum" onchange="UpdateSearch()">
</form>
Javascript
function updateSearch(){
$.each($("#results-form").serializeArray(),function(){
console.log("value: "+this.value+" data: "+this.data+" title: "+this.title);
if(this.value == this.title){
this.value = '';
}
});
var FormData = $("#results-form :input[value!='']").serialize();
console.log(FormData);
$(".defaultText").blur();
}
$(document).ready(function () {
$(".defaultText").focus(function (srcc) {
if ($(this).val() == $(this)[0].title) {
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".defaultText").blur(function () {
if ($(this).val() == "") {
$(this).addClass("defaultTextActive");
$(this).val($(this)[0].title);
}
});
$(".defaultText").blur();
});
Console Output
value: 3 data: undefined title: undefined
value: Maximum data: undefined title: undefined
Try this:
var arr = $("#results-form").serializeArray();
$.each(arr, function (i, input) {
var value = input.value;
var $elem = $("[name='" + input.name + "']");
var data = $elem.attr('data');
var title = $elem.attr('title');
console.log("value: " + value + " data: " + data + " title: " + title );
// You can process the parameters here now
});
I am using MVC3 in my project.
I have a view with around 2-12 div tags it depends on how many questions there is, if there is 5 questions there is 5 div tags that looks like an answer form. all these div tags are inside one form.
Each div tag have a hiddenfield, textarea and a DropDownList. values inside those fields are used by ajax post that takes the values inside the fields and posts it to my controller.
So far I am able to post the first div tag with my code, but the rest of the div tags aint getting posted. What I am looking for is to be able to post all the div tags one by one when "save all" button is clicked. Also all the div tags have the same class name: "wizard-step2". They all also have a ID which is unique and the value of the ID is the QuestionID taken from the database.
Here is my jquery code for the post:
$("saveall").click(function() {
$('#loading2').show();
setTimeout(function () { $("#loading2").hide(); }, 400);
var $step = $(".wizard-step2"); // show all steps
var Comment = $step.find(".Comment").val();
var QuestionID = $step.find(".QuestionID").val();
var Grade = $step.find(".Grade").val();
var data =
{
Comment: Comment,
QuestionID: QuestionID,
Grade: Grade
};
$.post('#Url.Action("AnswerForm", "AnswerNKI")', data, function () {
});
});
The following code will only save the first div tag but not the rest.
this is my HTML:
#{
int nr = 1;
foreach (SelectedQuestionViewModel items in Model.AllSelectedQuestions)
{
<div class="wizard-step2" id="#items.QuestionID">
<br/>
<br/>
<p>#(nr++). #items.SelectedQuestionText <span class="b">Betyg:
#{
var selectListItems = (new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Select(i => new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = (items.Grade.HasValue && i == items.Grade.Value) });
#Html.DropDownList("selectetListItems", selectListItems, "n/a", new { #class = "Grade" })
}</span></p>
<div class="editor-field">
#Html.TextArea("Comment", items.Comment, new { #id = "selectstyle3", #class = "Comment" })
</div>
<br/>
<br/>
#Html.Hidden("QuestionID", items.QuestionID, new { #id = "SelectedQuestions", #class = "QuestionID" })
<br/>
</div>
}
}
Any help is appreciated.
Thanks in advance!
Use the .each() function to iterate over the divs, and send an AJAX post for each individual one. Without seeing the HTML structure I can only guess based on what you already had, but I think the following should work:
$("saveall").click(function() {
$('#loading2').show();
setTimeout(function () { $("#loading2").hide(); }, 400);
$(".wizard-step2").each(function(index, step) {
var Comment = step.find(".Comment").val();
var QuestionID = step.find(".QuestionID").val();
var Grade = step.find(".Grade").val();
var data = {
Comment: Comment,
QuestionID: QuestionID,
Grade: Grade
};
$.post('#Url.Action("AnswerForm", "AnswerNKI")', data, function () {
});
});
});
Try this one... it will collect all your divs into one single array, and using ajax post will post the data...
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(document).ready(function () {
$("#Submit").click(function () {
var QuestionAnswerArray = [];
var QuestionAnswerLength = $(".wizard-step2").length;
$(".wizard-step2").each(function (i) {
var test = $(this).find("select,textarea, input").serializeObject()
QuestionAnswerArray.push(test);
if ((i + 1) == QuestionAnswerLength) {
$.ajax({
type: 'POST',
url: '/../AnswerNKI/AnswerForm',
data: JSON.stringify(QuestionAnswerArray),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (return_flag) {
if (return_flag == true) {
alert("Question and Answers Saved Succesfully!");
} else {
alert("Error Occured");
}
}
});
}
});
});
});
and in your controller...
[HttpPost]
public ActionResult AnswerForm(Answers[] answers)
{
foreach (var item in answers)
{
// do whatever you want here
}
return View();
}
I had to do a for loop this is the correct answer:
var $step = $(".wizard-step2"); // get current step
for (var i = 0; i < $step.length; i++) {
var allsteps = $(".wizard-step2");
var Allsteps = $(allsteps[i]);
var Comment = Allsteps.find(".Comment").val();
var QuestionID = Allsteps.find(".QuestionID").val();
var Grade = Allsteps.find(".Grade").val();
var data =
{
Comment: Comment,
QuestionID: QuestionID,
Grade: Grade
};
$.post('#Url.Action("AnswerForm", "AnswerNKI")', data, function () {
if (Comment != null && Grade > 0) {
$('a[data-id="' + QuestionID + '"]').removeClass("unfinished");
$('a[data-id="' + QuestionID + '"]').addClass("completed");
} else {
$('a[data-id="' + QuestionID + '"]').removeClass("completed");
$('a[data-id="' + QuestionID + '"]').addClass("unfinished");
}
});
}
How can I insert text/code at the cursors place in a div created by NicEdit?
I've tried to read the documentation and create my own plugin, but I want it to work without the tool bar (Modal Window)
This is a quick solution and tested in firefox only. But it works and should be adaptable for IE and other browsers.
function insertAtCursor(editor, value){
var editor = nicEditors.findEditor(editor);
var range = editor.getRng();
var editorField = editor.selElm();
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
value +
editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
}
Insert Html Plugin
Don't know if this will help or not, but this is the plugin I created for inserting Html at the cursor position. The button opens a content pane and I just paste in the html I want and submit. Works for me!
var nicMyhtmlOptions = {
buttons : {
'html' : {name : 'Insert Html', type : 'nicMyhtmlButton'}
},iconFiles : {'html' : '/nicedit/html_add.gif'}
};
var nicMyhtmlButton=nicEditorAdvancedButton.extend({
addPane: function () {
this.addForm({
'': { type: 'title', txt: 'Insert Html' },
'code' : {type : 'content', 'value' : '', style : {width: '340px', height : '200px'}}
});
},
submit : function(e) {
var mycode = this.inputs['code'].value;
this.removePane();
this.ne.nicCommand('insertHTML', mycode );
}
});
nicEditors.registerPlugin(nicPlugin,nicMyhtmlOptions);
I used the html_add icon from Silk Icons, pasted onto a transparent 18 x 18 and saved as gif in the same folder as nicEditorIcons.gif.
It works for me when I use:
function neInsertHTML(value){
$('.nicEdit-main').focus(); // Without focus it wont work!
// Inserts into first instance, you can replace it by nicEditors.findEditor('ID');
myNicEditor.nicInstances[0].nicCommand('InsertHTML', value);
}
The way I solved this was to make the nicEdit Instance div droppable, using jQuery UI; but to also make all of the elements within the div droppable.
$('div.nicEdit-main').droppable({
activeClass: 'dropReady',
hoverClass: 'dropPending',
drop: function(event,ui) {
$(this).find('.cursor').removeClass('cursor');
},
over: function(event, ui) {
if($(this).find('.cursor').length == 0) {
var insertEl = $('<span class="cursor"/>').append($(ui.draggable).attr('value'));
$(this).append(insertEl);
}
},
out: function(event, ui) {
$(this).find('.cursor').remove();
},
greedy: true
});
$('div.nicEdit-main').find('*').droppable({
activeClass: 'dropReady',
hoverClass: 'dropPending',
drop: function(event,ui) {
$(this).find('.cursor').removeClass('cursor');
},
over: function(event, ui) {
var insertEl = $('<span class="cursor"/>').append($(ui.draggable).attr('value'));
$(this).append(insertEl);
},
out: function(event, ui) {
$(this).find('.cursor').remove();
},
greedy: true
});
Then make your code or text draggable:
$('.field').draggable({
appendTo: '.content', //This is just a higher level DOM element
revert: true,
cursor: 'pointer',
zIndex: 1500, // Make sure draggable drags above everything else
containment: 'DOM',
helper: 'clone' //Clone it while dragging (keep original intact)
});
Then finally make sure you set the value of the draggable element to what you want to insert, and/or modify the code below to insert the element (span) of your choice.
$sHTML .= "<div class='field' value='{{".$config[0]."}}'>".$config[1]."</div>";
A response to #Reto: This code works, I just needed to add some fix because it doesn't insert anything if text area is empty. Also it adds only plain text. Here is the code if anybody need it:
if(editorField.nodeValue==null){
editor.setContent('<strong>Your content</strong>');
}else{
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
'<strong>Your content</strong>' +
editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
editor.setContent(editorField.nodeValue);
}
Change follwoing in NicEdit.js File
Updated from Reto Aebersold Ans It will handle Null Node exception, if text area is empty
update: function (A) {
(this.options.command);
if (this.options.command == 'InsertBookmark') {
var editor = nicEditors.findEditor("cpMain_area2");
var range = editor.getRng();
var editorField = editor.selElm();
// alert(editorField.content);
if (editorField.nodeValue == null) {
// editorField.setContent('"' + A + '"')
var oldStr = A.replace("<<", "").replace(">>", "");
editorField.setContent("<<" + oldStr + ">>");
}
else {
// alert('Not Null');
// alert(editorField.nodeValue + ' ' + A);
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) + A + editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
}
}
else {
// alert(A);
/* END HERE */
this.ne.nicCommand(this.options.command, A);
}
This function work when nicEdit textarea is empty or cursor is in the blank or new line.
function addToCursorPosition(textareaId,value) {
var editor = nicEditors.findEditor(textareaId);
var range = editor.getRng();
var editorField = editor.selElm();
var start = range.startOffset;
var end = range.endOffset;
if (editorField.nodeValue != null) {
editorField.nodeValue = editorField.nodeValue.substring(0, start) +
value +
editorField.nodeValue.substring(end, editorField.nodeValue.length);
}
else {
var content = nicEditors.findEditor(textareaId).getContent().split("<br>");
var linesCount = 0;
var before = "";
var after = "";
for (var i = 0; i < content.length; i++) {
if (linesCount < start) {
before += content[i] + "<br>";
}
else {
after += content[i] + "<br>";
}
linesCount++;
if (content[i]!="") {
linesCount++;
}
}
nicEditors.findEditor(textareaId).setContent(before + value + after);
}
}