add click event to auto complete - javascript

this is my AutoComplete code :
<link href="JostejuFile/css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="JostejuFile/scripts/jquery-1.4.1.min.js"></script>
<script src="JostejuFile/scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtSearch.ClientID%>").autocomplete("Handler/Search_CS.ashx", {
width: 200,
formatItem: function (data, i, n, value) {
return "<img style = 'width:50px;height:50px' src='PRupload/" +
value.split("-")[1] + "'/>" + value.split("-")[0];
},
formatResult: function (data, value) {
return value.split("-")[0];
}
});
});
</script>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
I want to fire an event on the click or selection of an item from the autocomplete list.Can anyone please help me out with this?

You can always add code for select event in autocomplete:
i.e.
$( ".selector" ).autocomplete({
select: function( event, ui ) {}
});
Reference:
http://api.jqueryui.com/autocomplete/#event-select

Related

how to use variable inside my function in javasript?

<script type='text/javascript'>
$(document).ready(function () {
$("#q").keyup(function () {
var value = $('#q').val()
$.getJSON("{% url 'api:api-root' %}" + "bankdetailapi/?q=" + value, function (data) {
var text = []
for (var i = 0; i < 5; ++i) { text.push(data.results[i].ifsc) }
// var text = `IFSC: ${data.results.ifsc}`
if (document.getElementById("q").value.length == 0) { text = [] }
// console.log(text)
$('#q').hover(
function () {
console.log(text)
$("q").autocomplete({
source: text,
delay: 500
});
}, function () {
$("#q").autocomplete("disabled");
})
})
})
})
</script>
I have created variable text to store results from get request. My autocomplete function is inside the getJSON function. i have checked consolelog if its printing anything. Inside of hover function it doesnt print anything, but outside statement when commented out prints results. I dont understand why this is happening. I need this so that my autocomplete wont show results when user deletes all input or is not hovering over it.
Update
I changed $(this).hover to $("#q").hover, as it would trigger hover event for wherever mouse is. still nothing changed
I think you can simplify this a bit and use the actual enable/disable.
I used the long form of the hover (mouseenter, mouseleave) for clarity
$(function() {
$("#q").on('keyup', function() {
var value = $('#q').val();
/* $.getJSON("{% url 'api:api-root' %}" + "bankdetailapi/?q=" + value, function(data) {
var text = [];
for (var i = 0; i < 5; ++i) {
text.push(data.results[i].ifsc);
}
// var text = `IFSC: ${data.results.ifsc}`
if (document.getElementById("q").value.length == 0) {
text = [];
}
});
*/
}).on('mouseenter', function() {
console.log("Initial:", $(this).val());
$(this).autocomplete("enable");
}).on("mouseleave", function() {
// this will break the autocomplete (not choose a value) so you would have to do that manually
// $(this).autocomplete("disable");
}).autocomplete({
source: [{
label: "Choice1",
value: "value1"
}, {
label: "Choice2",
value: "value2"
}, {
label: "Party",
value: "beer"
}],
delay: 500,
select: function(event, selectedObject) {
jQuery(this).val(selectedObject.item.value);
}
});
});
.ui-autocomplete {
position: absolute;
cursor: default;
z-index: 1001 !important
}
.ui-front {
z-index: 1500 !important;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/cupertino/jquery-ui.min.css" integrity="sha512-ug/p2fTnYRx/TfVgL8ejTWolaq93X+48/FLS9fKf7AiazbxHkSEENdzWkOxbjJO/X1grUPt9ERfBt21iLh2dxg==" crossorigin="anonymous"
referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/cupertino/theme.min.css" integrity="sha512-adRIgePtMQgAVB+Mfkhl+Nyva/WllWlFzJyyhYCjznU3Di+Z4SsYi1Rqsep11PYLpUsW/SjE4NXUkIjabQJCOQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div class="ui-widget">
<label for="q">Tags: </label>
<input id="q" type="text">
</div>
Consider an alternative example.
$(function() {
$("#q").autocomplete({
source: function(request, response) {
var myUrl = "{% url 'api:api-root' %}" + "bankdetailapi/";
$.ajax({
url: myUrl,
data: {
q: request.term
},
success: function(data) {
var text = [];
$.each(data.results, function(i, res) {
if (i < 5) {
text.push(res.ifsc);
}
});
response(text);
}
})
},
delay: 500,
minLength: 0
}).hover(function() {
if ($(this).val() != "") {
$(this).autocomplete("search", $(this).val());
}
}, function() {
$(this).autocomplete("close");
});
});
.ui-autocomplete {
position: absolute;
cursor: default;
z-index: 1001 !important
}
.ui-front {
z-index: 1500 !important;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="q">Tags: </label>
<input id="q" type="text">
</div>
See More: https://api.jqueryui.com/autocomplete/

How to pass textbox client ID to JavaScript function

I have a JS function to make textbox operation. When I sent textbox client ID, I am receiving this syntax error:
JavaScript runtime error: Syntax error, unrecognized expression: #<%=txtEposta.ClientID%>
How can I fix this error? I am very new to JavaScript. Whatever I tried I cannot find a solution. Please help.
function SearchText(clientID) {
console.log("#" + clientID);
var availableTags = ["gmail.com", "hotmail.com", "mynet.com", "yahoo.com", "outlook.com", "windowslive.com"];
$("#"+clientID).autocomplete({
source: availableTags,
matchCase: false,
focus: function (event, ui) {
var oldValue = $("#" + clientID).val();
var value = oldValue + ui.item.value;
event.preventDefault();
$("#" + clientID).val(value);
},
select: function (event, ui) {
var oldValue = $("#" + clientID).val();
var value = oldValue + ui.item.value;
$("#" + clientID).val(oldValue);
event.preventDefault();
},
minLength: 0
});
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="TextBoxControl.WebUserControl1" %>
<link href="/Script/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.24.js"></script>>
<script type="text/javascript" src="../common.js"></script>>
<div>
<asp:Textbox runat="server" ID="txtEposta" MaxLength="100" Width="250px" onKeyPress="javascript:SearchText('<%=txtEposta.ClientID%>');"
ControlType="AlpfaNumericAndSymbols" AllowSpaces="False" Visible="true"></asp:Textbox>
</div>
You could simply replace the txtEposta.ClientID with this.
<asp:Textbox runat="server" ID="txtEposta" onKeyPress="javascript:SearchText(this);"
<script>
function SearchText(element) {
alert(element.id);
}
</script>
If you really want to use ClientID you will have to add it programatically
<asp:TextBox runat="server" ID="txtEposta"></asp:TextBox>
<script>
function SearchText(element) {
alert(element);
}
</script>
and then in Page_Load
txtEposta.Attributes.Add("onKeyPress", string.Format("javascript:SearchText('{0}');", txtEposta.ClientID));
Set the property ClientIDMode in you Textbox to Static. Thes will make the ClientID be the same as the id on server side. Don't forget to change the onKeyPress argument.
<asp:Textbox runat="server" ID="txtEposta" ClientIDMode="Statis" MaxLength="100" Width="250px" onKeyPress="javascript:SearchText('txtEposta');"
ControlType="AlpfaNumericAndSymbols" AllowSpaces="False" Visible="true"></asp:Textbox>

jQuery blur event not fired for table cell

I'm loading a table dynamically using jQuery ajax, the rows of the table has "contenteditable=true", I'm trying to listen on blur event for every cell, so that it triggers a function to update that cell dynamically.
The problem is that the event blur isn't fired at all, I've tried different selectors(table,tbody, and finally the whole document), but all in vain.
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src='jquery-1.8.3.js'></script>
<link rel="stylesheet" href='jquery-ui-1.8.7.custom.css' type="text/css">
<?php
include './datatable_include.php';
?>
<script type="text/javascript">
$(function () {
$.ajax({//create an ajax request to load_page.php
type: "GET",
url: "load_table.php",
dataType: "html", //expect html to be returned
success: function (response) {
$('#dataTable').find('tbody').html(response);
initDataTable('#dataTable', null);
}
});
});
$(document).bind("blur", "td", (function () {
// this code isn't reached
alert("ahoo");
var id = $(this).attr("id");
var name = $(this).attr("name");
var message_status = $("#status");
var value = $(this).text();
$.post('update_table.php', "id=" + id + "&" + name + "=" + value, function (data) {
if (data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function () {
message_status.hide()
}, 3000);
}
});
}));
</script>
</head>
<body>
<table id="dataTable" width="700px" >
<thead>
<tr>
<th>Name</th>
<th>ID</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
try
$(document).bind("td").blur(function()
{
});
seems that table td isn't a standard focusable element so you can't blur it.
try to add the tabsindex property to each td
<td tabindex="1">focus on me</td>
the definition of bind function is as follows:
.bind( eventType [, eventData ], handler )
so, you should do:
$('td').bind('blur', function(){
//event handler statement goes here
});
And as mentioned by #paul roub in the comments above, you should be using live() function, as you are creating the td elements dynamically.
$('td').live('blur', function(){
//event handler statement goes here
});

jquery autocomplete highlighting

How can I make my jquery autocomplete highlight what the user is typing in in any autocompleted results? The code I am using is:
$("#keyword").autocomplete({
source: "ajax/autocomplete.php?action=keyword",
minLength: 2
});
Tried this implemented from the link tomasz posted:
$("#keyword").autocomplete({
source: "ajax/autocomplete.php?action=keyword",
highlight: function(value, term) {
return value.replace(new RegExp("("+term+")", "gi"),'<b>$1</b>');
},
minLength: 2
});
No luck there either. jQuery autocomplete seems to hate me.
Update: Thanks to David Murdoch, I now have an answer! See #Herman's copy of the answer below.
Thanks goes to David Murdoch at http://www.vervestudios.co/ for providing this useful answer:
$.ui.autocomplete.prototype._renderItem = function( ul, item){
var term = this.term.split(' ').join('|');
var re = new RegExp("(" + term + ")", "gi") ;
var t = item.label.replace(re,"<b>$1</b>");
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + t + "</a>" )
.appendTo( ul );
};
$("#keyword").autocomplete({
source: "ajax/autocomplete.php?action=keyword",
minLength: 2
});
Thought somone might find this useful. it's a complete HTML doc that makes uses of the above principles. I used it as a protoype for some of my work.
<html xmlns="http://www.w3.org/1999/xhtml">
<!--
orders.html simply returns the following text
Basketball#Football#Baseball#Helicopter#gubbins#harry potter#banyan
-->
<head id="Head1" runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
function loadData() {
var sURL = "orders.htm";
$.ajaxSetup({ cache: false });
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
var term = this.term.split(' ').join('|');
var re = new RegExp("(" + term + ")", "gi");
var t = item.label.replace(re, "<b>$1</b>");
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + t + "</a>")
.appendTo(ul);
};
$.get(sURL, function (responseText) {
data = responseText.split('#');
$("#txtSearch").autocomplete({
//source: availableSports
source: data,
minLength: 2
});
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">
Enter data:
</label>
<input type="text" id="txtSearch" class="autosuggest" onkeyup="loadData();" />
</div>
</form>
</body>
</html>
Hopefully it'll help someone as it helped me.

Internet explorer only executing function inside jQuery ajax success response once even though there are three requests

I have a function that uses jQuery.load() to call in 3 snippets of forms from different pages and then on the success text status it tries to load a colour picker:
$(document).ready(function() {
function ajax_form(putloadingboxhere, putsnippethere, snippeturl) {
$(putsnippethere).load(snippeturl, function (responseText, textStatus, XMLHttpRequest, ) {
if (textStatus == "success") {
alert('One')
$("input.pickcolor").ColorPicker({
onShow: function (colpkr) {
$(colpkr).fadeIn(500);
return false;
},
onSubmit: function(hsb, hex, rgb, el) {
$(el).val(hex);
$(el).ColorPickerHide();
$(el).siblings('.colorpreview').css('background-color', '#' + hex);
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
})
.bind('keyup', function(){
$(this).ColorPickerSetColor(this.value);
});
alert('Two')
}
if (textStatus == "error") {
// Show error message
}
});
}
ajax_form('tab_box', '#formone', 'snippet_one.htm #snippet');
ajax_form('tab_box', '#formtwo', 'snippet_two_copy.htm #snippet');
ajax_form('tab_box', '#formthree', 'snippet_three.htm #snippet');
});
It works fine in Firefox and Safari but (surprise, surprise) IE has a problem with it. I have added an alert to see what is going on before and after one of the functions.
FF & Safari & IE8: Alert 'one' and Alert 'two' appear three times as expected and colour picker appears.
IE6 & 7: Alert 'one' shows three times and colour picker does not appear.
Any help would be great! Cheers.
EDIT
The line IE is referring to when it throws this error:
'Error: Object doesn't support this property or method.'
is:
$('input.pickcolor').ColorPicker
Anyone got any insights? Thanks
Have you tied ".live" instead of ".bind"?
I just test the script and the only problem I had is that the function "load" has a comma in the last parameter, It works fine in IE6 and IE7.
$(putsnippethere).load(snippeturl, function (responseText, textStatus, XMLHttpRequest, )
Update all script:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/colorpicker.css" type="text/css" />
<link rel="stylesheet" media="screen" type="text/css" href="css/layout.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="js/colorpicker.js"></script>
<script type="text/javascript" src="js/eye.js"></script>
<script type="text/javascript" src="js/utils.js"></script>
<script type="text/javascript" src="js/layout.js?ver=1.0.2"></script>
<title>load</title>
</head>
<body>
<div id="formone"></div>
<div id="formtwo"></div>
<div id="formthree"></div>
<input id="i1" class="pickcolor" type="text" /><br />
<input id="i2" class="pickcolor" type="text" /><br />
<input id="i3" class="pickcolor" type="text" /><br />
<pre style="text-align:left;width:600px;" id="mydebug"></pre>
</body>
</html>
<script>
$(function() {
addDebug = function(text){
$("#mydebug").append(text+"<br />");
}
function ajax_form(putloadingboxhere, putsnippethere, snippeturl) {
$(putsnippethere).load(snippeturl, function (responseText, textStatus, XMLHttpRequest) {
if (textStatus == "success") {
addDebug(putsnippethere + " :: One");
var lstElPickcolor = $("input.pickcolor");
addDebug(putsnippethere + " :: Length inputs : " + lstElPickcolor.length);
$.each(lstElPickcolor, function(i, val){
addDebug(putsnippethere + " :: add ColorPicker for input.id=" + $(val).attr('id'));
$(val).ColorPicker({
onShow: function (colpkr) {
$(colpkr).fadeIn(500);
return false;
},
onSubmit: function(hsb, hex, rgb, xel) {
$(xel).val(hex);
$(xel).ColorPickerHide();
$(xel).siblings('.colorpreview').css('background-color', '#' + hex);
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
});
addDebug(putsnippethere + " :: unbind event keyup for input.id=" + $(val).attr('id'));
$(val).unbind('keyup');
addDebug(putsnippethere + " :: bind event keyup for input.id=" + $(val).attr('id'));
$(val).bind('keyup', function(){
$(this).ColorPickerSetColor(this.value);
});
});
addDebug(putsnippethere + " :: Two");
addDebug(" ");
}
if (textStatus == "error") {
// Show error message
}
});
}
ajax_form('tab_box', '#formone', 'snippet_one.htm #snippet');
ajax_form('tab_box', '#formtwo', 'snippet_two_copy.htm #snippet');
ajax_form('tab_box', '#formthree', 'snippet_three.htm #snippet');
});
</script>

Categories

Resources