Create link in JQuery Autocomplete - javascript

I am having difficulty figuring where to insert and how to make a click function when users click/select an autocomplete item. I then want to do a DB query with the clicked item.
My current autocomplete script:
$("#search_customer").autocomplete({
source: "search.php",
minLength: 1,
response: function(event, ui) {
if (!ui.content.length) {
var create_customer = alert('bla bla...');
if (create_customer)
{
console.log('yes');
}
else
{
console.log('no');
}
}
}
});

Use select callback of jquery ui autocomplete
e.g
$("#search_customer").autocomplete({
source: "search.php",
minLength: 1,
select: function(event,ui) {
var label = ui.item.label; // label of selected item
var value = ui.item.value; // value of selected item
// then make an ajax call here to get the data from db.
},
response: function(event, ui) {
if (!ui.content.length) {
var create_customer = alert('bla bla...');
if (create_customer)
{
console.log('yes');
}
else
{
console.log('no');
}
}
}
});
Hope this helps.

Related

jquery autocomplete for a textbox should not allow data other than the autocomplete list

jquery autocomplete for a textbox should not allow data other than the autocomplete list.,but the problem is i need to allow only data from the list autocomplete list but not any other data, even if the user enter any another data we i need to show a message that please select from the autocomplete list.
The link show below is also allowing any data other than the autocomplete suggestions:
$("#field").autocomplete({
source: countries_starting_with_A,
minLength: 1,
select: function(event, ui) {
// feed hidden id field
$("#field_id").val(ui.item.id);
// update number of returned rows
$('#results_count').html('');
},
open: function(event, ui) {
// update number of returned rows
var len = $('.ui-autocomplete > li').length;
$('#results_count').html('(#' + len + ')');
},
close: function(event, ui) {
// update number of returned rows
$('#results_count').html('');
},
// mustMatch implementation
change: function (event, ui) {
if (ui.item === null) {
$(this).val('');
$('#field_id').val('');
}
}
});
http://jsfiddle.net/handtrix/32Bck/
There are lots of ways to do this. Here is one suggestion:
Working Example: http://jsfiddle.net/Twisty/32Bck/560/
HTML
<div class="ui-widget" style="position: relative;">
<input type="text" placeholder="type something ..." id="suggest" />
</div>
CSS
body {
padding: 30px;
}
input.ui-state-alert {
border: 1px inset #F00;
}
JavaScript
var makeSelect = false;
$(document).ready(function() {
function requiredValid(target) {
target = $(target);
// Return Focus
target.focus();
// Add alert class
target.addClass("ui-state-alert");
$("<div>", {
class: "required-alert-text",
style: "color: #F00; font-size: 10px; display: inline-block; position: absolute;"
}).html("Must select from list.").insertAfter(target).position({
my: "bottom",
at: "top+5",
of: target
});
}
$("#suggest").autocomplete({
delay: 100,
source: function(request, response) {
// Suggest URL
var suggestURL = "http://suggestqueries.google.com/complete/search?client=chrome&q=" + request.term;
// JSONP Request
$.ajax({
method: 'GET',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
url: suggestURL
})
.success(function(data) {
response(data[1]);
});
},
select: function(e, ui) {
makeSelect = true;
},
close: function(e, ui) {
if (makeSelect) {
makeSelect = false;
$(".ui-state-alert").removeClass("ui-state-alert");
$(".required-alert-text").remove();
} else {
requiredValid(this);
}
}
});
$(".ui-state-alert").on("blur", function() {
$(this).focus();
})
});
This will not cover all cases. Basically, we want to know if the user made a selection from the list. I created makeSelect and assigned it as false. We assume upfront that the user has not done this.
When the user selects a list option, select callback is triggered and updates out variable. This also triggers close callback as it is now closing the list. If the user has made a selection, we move one and reset for the next time. If not, we apply some techniques to alert the user and keep focus until they make a selection.

jQuery $(this).addClass not working

I have a list of textboxes in which a user can drop a letter but when a wrong letter is dropped inside the textbox I want to addClass("danger") I want to addClass only on the wrong letter textbox I have also attached a screenshot to illustrate the problem.
The textbox has a class with the name of box assigned.
Now my drop function is given below.
function dropabc(event) {
if ($(objBox).attr("correct1") != event.target.id) {
$(".imageError").fadeIn('slow').delay(1000).hide(0);
console.log("error");
$(this).addClass('danger');
} else {
console.log(event.target.id);
console.log("ok");
}
}
$(this).addClass("danger")
However, this is not working, I only want to add the danger class to the box on which a wrong value is dropped.
//makes all the textbox red
$(".box").addClass("danger")
Any help would be very appreciated!
This is the jQuery UI drag and droppable function which is working fine:
var objBox;
$('.drag').draggable({
revert: true,
helper: 'clone',
cursor: 'pointer',
start: function(event, ui) {
$(this).fadeTo('fast', 0.5);
objBox=$(this);
},
stop: function(event, ui) {
$(this).fadeTo(0, 1);
}
});
$("#textbox, .box").droppable({
hoverClass: "hoverPath",
drop: function(event, ui) {
var $this = $(this);
if ($this.val() == '') {
$this.val(ui.draggable.text());
$(this).addClass("checkDiv");
$(this).each(function(i, el){
$(el).addClass(myid[3]);
});
}
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
console.log(empty.length);
}
else{
console.log("done");
}
}
});
This is the PHP code which is echo the number of textbox:
for($x = 0 ; $x < count($code_words); $x++){
echo "<input id='".$code_words[$x]."' ondrop='dropabc(event)' class='box' type='textbox'/>";
}
You're just running a function when you embed the ondrop event inside your input tag.
So instead of embedding it try using the jQuery on("drop").
$(document).on("drop", ".box", function(event){
if ($(objBox).attr("correct1") != event.target.id) {
$(".imageError").fadeIn('slow').delay(1000).hide(0);
console.log("error");
$(this).addClass('danger');
} else {
console.log(event.target.id);
console.log("ok");
}
})
Great it helped you :)
Cheers,

Jquery onchange is not working

<script>
$(document).ready(function(){
$("#customer").autocomplete("barcode.php", {
selectFirst: true
});
});
</script>
<script>
$(document).ready(function() {
$("#customer").change(function (e) {
var item = $("#customer").val();
$.post("add", {"data[Sales][item]": item }, function (data) {
$('#details').html(data);
});});
});
</script>
<input type="text" id='customer' name="data[Sales][customer]" class="input-small focused" autocomplete='off'>
<div id='details'></div>
Autocomplete is working fine . On change is not working properly . If I enter all text without selecting through autocomplte then onchange script is working . If I selected trough autocompleted then I pressed tab key then onchange is not working . Its not showing any result.
Use .keypress instead of change
See documentation of keypress
var item = $("#customer").val(); ---> Change Here.. That's It.
If you are using the jQuery autocomplete plugin then use its onChange method
Ex.
$( ".selector" ).autocomplete({
selectFirst: true,
change: function( event, ui ) {
var item = $("#select01").val();
$.post("add", {"data[Sales][item]": item }, function (data) {
$('#details').html(data);
});
// Add more code here!
}
});
You can use as following:
$("#customer").autocomplete("barcode.php", {
selectFirst: true,
select: function(e, ui) {
alert("selected!");
},
change: function(e, ui) {
alert("changed!");
}
});
$.post("add", {"data[Sales][item]": item }, function (data) {
$('#details').html(data);
});

Custom Autocomplete with jquery

I am working on jquery autocomplete custom data and display.I want to display some static dropdown on keypress in textbox.when user select that list item i want to add it to textbox.
the code which i have tested is
$('#uinput').keyup(function() {
var val = $('#uinput').val();
if(val.length>1) { // check length
// handle successful DWR response
//alert(data);
var b=[{value: "jquery-ui",
label: "jQuery UI",}];
$('#uinput').autocomplete({source:b,
select: function( event, ui ) {
$( "#uinput" ).val( ui.item.label+"="+document.getElementById('uinput').value );
return false;
}
}).data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li>" )
.data('item.autocomplete', item)
.append( "<a>" + item.label + "=" + document.getElementById('uinput').value + "</a>" )
.appendTo( ul );
};
} else {
$('#uinput').autocomplete([]); // clean
}
});
For reference what i want to do
custom autocomplete
I'm not exactly sure what you're trying to accomplish but I think I've put together this example that I think might help you
https://jsfiddle.net/mgxnxhs8/5/
here's my javascript
$(function () {
var availableTags = [{
label: "jQuery 1.9.1",
value: "http://code.jquery.com/jquery-1.9.1.js",
}, {
label: "jQuery 2.1.4",
value: "http://code.jquery.com/jquery-2.1.4.js",
}];
$('#uinput').autocomplete({
source: availableTags,
minLength: 0,
select: function (event, ui) {
$('#uoutput').val(ui.item.value);
return false;
}
}).focus(function () {
$(this).autocomplete("search");
});
});
The dropdown opens up when you enter the textbox and displays the "label" key of the tags. On Select(), it sets the value of another textbox to the "value" key of the selected tag.
Let me know if theres something I missed. Hope this helps

update the unselectable value (jquery)

i'm using selectable jquery, i want to cater the value for selectable once the use select or unselect the item. My problem is, the last value of unselectable won't update.
Full code here http://jsfiddle.net/duQH6/ When I select Mon and Tue, then I unselect the Tue, the value is updated, but then when I click Mon, the value is not updated. Please advice.
Here my jquery code
$(function() {
$("#selectday1").bind('mousedown', function (e) {
e.metaKey = true;
}).selectable();
});
$('document').ready(function(){
$( "#selectday1" ).selectable({
selected: function(event, ui) {
var result=[];
jQuery(".ui-selected", this).each(function()
{
result.push(this.id);
$("#days").val(result.join(','))
});
}
});
$( "#selectday1" ).selectable({
unselected: function(event, ui) {
var result=[];
jQuery(".ui-selected", this).each(function()
{
result.push(this.id);
$("#days").val(result.join(','))
});
}
});
});
Thanks..
The problem is, you are updating the days value within the each loop, so when you unselect the last element the loop callback is never executed, that is why it is happening.
The days value is supposed to be updated once the each() loop is completed.
$(document).ready(function () {
$("#selectday1").selectable({
selected: function (event, ui) {
var result = [];
jQuery(".ui-selected", this).each(function () {
result.push(this.id);
});
$("#days").val(result.join(','))
},
unselected: function (event, ui) {
var result = [];
jQuery(".ui-selected", this).each(function () {
result.push(this.id);
});
$("#days").val(result.join(','))
}
});
});
Demo: Fiddle
But it can be simplified to
jQuery(function ($) {
function serialize(event, ui) {
var result = $(this).find(".ui-selected").map(function () {
return this.id;
}).get();
$("#days").val(result.join(','))
}
$("#selectday1").selectable({
selected: serialize,
unselected: serialize
});
});
Demo: Fiddle

Categories