Im trying to use jquery ui for search bar autocomplete. When I use div id="inputs" autocomplete works fine, but if I use input id="inputs" it's not working and i need to use input in order to search works properly.
(function ($) {
$.fn.googleSuggest = function(opts){
opts = $.extend({service: 'web', secure: false}, opts);
var services = {
web: { client: 'hp', ds: '' },
}, service = services[opts.service], span = $('<span>');
opts.source = function(request, response){
$.ajax({
url: 'http'+(opts.secure?'s':'')+'://clients1.google.com/complete/search',
dataType: 'jsonp',
data: {
q: request.term,
nolabels: 't',
client: service.client,
ds: service.ds
},
success: function(data) {
response($.map(data[1], function(item){
return { value: span.html(item[0]).text() };
}));
}
});
};
return this.each(function(){
$(this).autocomplete(opts);
});
}
}(jQuery));
$.each("web".split(" "), function(i, v){
var div = $("<div>").appendTo("#inputs")
, input = $("<input>").appendTo(div)
input.googleSuggest({ service: v });
});
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" type="text/css" rel="stylesheet"/>
<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>
</head>
<body>
<div id="inputs"></div>
</body>
</html>
<input> tags can't have child elements, so you can't append nodes to them.
It looks like what you're trying to append is a div, which contains another input, which you run googleSuggest() against:
var div = $("<div>").appendTo("#inputs")
, input = $("<input>").appendTo(div)
input.googleSuggest({ service: v });
So it seems that you don't need to append anything. Instead, just put googleSuggest on the <input> that's already in the DOM:
$('#inputs').googleSuggest({ /*...*/ })
Related
I'm migrating the select2 component from 3.4.5 to 4.0.13 (to solve this issue: https://snyk.io/test/npm/select2/3.4.5) but I've a lot of wrapped code around it and I'm having a lot of problems upgrading.
I've a sandbox and I found the first problems there:
If I use a "div" to create the component (as in my application), the (obsolete) callback "initSelection" works as I need, but then I've no way to get the selected values from the component. And I think that is the problem because the elements of the "initSelection" are shown but not "set".
var sourceData = [
{id:"1",text:"Hello!"}, {id:"2",text:"Welcome!"}, {id:"3",text:"Good bye!"}, {id:"3",text:"Good night!"}
];
$(document).ready(function() {
$('.mpm-select').select2({
data: sourceData,
multiple: true,
initSelection: function (element, callback) {
var data = sourceData;
$(element.val()).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
});
});
.mpm-select {
width: 100%;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.9/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" 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/select2/4.0.9/js/select2.full.min.js"></script>
<div class="mpm-select"></div>
If I use a "input" to create the component (it will requires some changes on my application), "initSelection" callback is not triggered on creation, but I can use the jQuery element to call val() function.
var sourceData = [
{id:"1",text:"Hello!"}, {id:"2",text:"Welcome!"}, {id:"3",text:"Good bye!"}, {id:"3",text:"Good night!"}
];
$(document).ready(function() {
$('.mpm-select').select2({
data: sourceData,
multiple: true,
initSelection: function (element, callback) {
var data = sourceData;
$(element.val()).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
});
});
.mpm-select {
width: 100%;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.9/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" 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/select2/4.0.9/js/select2.full.min.js"></script>
<input class="mpm-select"></div>
How I can get the values of the select2 element when it's a "div" or how can I force to trigger "initSelection" callback when it's an "input"?
I have page to show data using jquery and bootstrap table in laravel :
In body I have hidden type to parse value to jquery :
<input type="hidden" name="compName" id="compName" value="">
The jquery code :
<script type="text/javascript">
$(document).ready(function(){
$('#attendanceTable').bootstrapTable({
classes: 'table table-striped',
striped: true,
formatLoadingMessage: function(){ return '<img src="public/assets/images/cui-loading.gif" width="30px"/>';},
url: '{{ URL::route("get_data_attendance") }}',
queryParams:function(p){
p.iSearch = $('#iSearch').val();
p.compName = $('#compName').val();
return p;
},
pagination:true,
sidePagination:'server',
columns: [{
field:'nik',
title:'NIK',
},{
field:'date',
title:'DATE',
},{
field:'staffname',
title:'NAME',
},{
field:'in',
title:'IN',
},{
field:'out',
title:'OUT',
}]
});
$('.filterTable').on('click',function(e){
e.preventDefault();
$('#attendanceTable').bootstrapTable('refresh', {
url: 'http://portal.rodalink.com/attendance/data',
queryParams:function(p){
p.iSearch = $('#iSearch').val();
p.compName = $('#compName').val();
return p;
}
});
});
document.addEventListener("DOMContentLoaded", function(event) {
$('.filterTable').trigger('click');
});
});
The problem is : jquery cant get the compName parameter when page is loaded, but if I click search button or refresh the page jquery can get the compName parameter. How to handle this issue? Thanks!
I'm trying to change the color of an SVG object with a jQuery, but after that i want to reset all fill attribute in class st24.
But after reset setAttribute doesn't work.
//Автокомплит
$(function() {
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
cache: true,
url: "http://127.0.0.1/json.php",
dataType: "json",
success: function(data) {
response($.map(data, function(item){
return {
label: item.username,
placeId: item.LocationInfo.placeId,
}}));
}
});
},
minLength: 2,
select: function(event,ui) {
$('#users').val(ui.item.username);
$('#placeId').val(ui.item.placeId);
console.log(ui.item.placeId);
console.log(svgdom);
var svgElement = svgdom.getElementById(ui.item.placeId);
//Если id елемента есть в svg файле - меняем аттрибур fill, если нет генерируем алерт
if (svgElement) {
var st24 = svgdom.getElementsByClassName("st24");
$.each(st24, function( i, val) {
val.setAttribute("fill", "none");
});
svgElement.setAttribute("fill", "#008000");
} else {
generate('information');
}
}
});
});
});
If i try this:
$.each(st24, function( i, val) {
val.setAttribute("fill", "#008000");
});
work perfect - all elements have this attribute, but when i change setAttribute fill to none, and add this line: svgElement.setAttribute("fill", "#008000"); after this code, it doesn't work - why ?
Update:
This all my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="libs/jquery-2.1.1.min.js"></script>
<script src="libs/jquery-ui-1.10.4.js" type="text/javascript"></script>
<script src="libs/jquery.panzoom.js"></script>
<script src="libs/jquery.mousewheel.js"></script>
<script src="libs/noty/packaged/jquery.noty.packaged.min.js" type="text/javascript"></script>
<script src="libs/svg-pan-zoom.min.js"></script>
<link href="css/style.css" rel="stylesheet">
<link type="text/css" href="css/jquery-ui-1.10.4.custom.css" rel="stylesheet" />
</head>
<body>
<a id="link" href="admin.html">Admin</a>
<div class="ui-widget">
<label for="users">users: </label>
<input id="users" type="text" />
<input readonly="readonly" id="placeId" name="placeId" />
</div>
<embed src="svg/5.svg" width="900" height="900" id="imap"/>
<script>
//Всплывающие сообщения
function generate(type) {
var n = noty({
text : "Sorry place not found",
type : type,
dismissQueue: true,
layout : 'topCenter',
theme : 'defaultTheme',
timeout: 2000,
});
}
function generateInf() {
generate('information');
}
// Начинаем работу когда страница полностью загружена (включая графику)
$(window).load(function () {
// Получаем доступ к SVG DOM
var svgdom = document.getElementById('imap').getSVGDocument();
svgPanZoom('#imap', {
zoomEnabled: true,
controlIconsEnabled: true
});
function clearSvg() {
var st24 = svgdom.getElementsByClassName("st24");
$.each(st24, function(i, val) {
val.removeAttribute("fill");
});
}
function setColor(elem) {
elem.setAttribute("fill", "#008000");
}
//Автокомплит
$(function() {
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
cache: true,
url: "http://127.0.0.1/json.php",
dataType: "json",
success: function(data) {
response($.map(data, function(item){
return {
label: item.username,
placeId: item.LocationInfo.placeId,
}}));
}
});
},
minLength: 2,
select: function(event,ui) {
$('#users').val(ui.item.username);
$('#placeId').val(ui.item.placeId);
console.log(ui.item.placeId);
console.log(svgdom);
var svgElement = svgdom.getElementById(ui.item.placeId);
//Если id елемента есть в svg файле - меняем аттрибур fill, если нет генерируем алерт
if (svgElement) {
clearSvg();
setColor(svgElement);
} else {
generate('information');
}
}
});
});
});
</script>
</body>
</html>
Setting fill to none doesn't delete the fill. It is saying "this element has no fill". So setting fill on the <svg> parent doesn't override that. The value on the child takes precendence.
If you want to remove the fill setting from the children use
val.removeAttribute('fill');
Update
Try something like this:
if (svgElement) {
var st24 = svgdom.getElementsByClassName("st24");
$.each(st24, function( i, val) {
val.removeAttribute("fill");
});
svgElement.setAttribute("fill", "#008000");
} else ...
Update 2
Have a look at this fiddle. Hopefully it should help explain what I mean.
http://jsfiddle.net/gt7nd/1/
Use this
$(val).css('fill',"#008000");
or this
val.style.fill = "#000800"
My SVG code:
<g id="505Б-1" place="place" v:mID="1937" v:groupContext="shape" transform="translate(206.929,-334.488)" class="test">
<title>Circle, ellipse.1937</title>
<v:userDefs>
<v:ud v:nameU="visVersion" v:val="VT0(14):26"/>
</v:userDefs>
<path transform="" d="M0 837.64 A4.25197 4.25197 0 0 1 8.5 837.64 A4.25197 4.25197 0 1 1 0 837.64 Z" class="st24"/>
</g>
I use class "test" instead "st24", and everything works now!
Using JQuery UI widget to try and call in this js file of string data but getting 'no results found'. No console errors. I simply don't think I'm referencing this correctly as I'm not very proficient with jquery/js. If someone could point me in a direction, I'd appreciate it.
<input type="text" id="test" />
scripts
<script src='js/jquery-1.11.0.min.js'></script>
<script src="js/autocomplete/jquery-ui-1.10.3.custom.js" type="text/javascript" charset="utf-8"></script>
<script src="js/Providers.js" type="text/javascript" charset="utf-8"></script>
formatted in file
var providerdata=[{"ProviderID":"1","NAME":"name1"},{"ProviderID":"2","NAME":"name2"},{"ProviderID":"3","NAME":"name3"}];
calling
$('#test').autocomplete({
source: providerdata,
success: function(data) {
var cat_data = $.map(data.Providers, function(item) {
return {
value: item.NAME,
label: item.NAME,
};
});
$("#test").autocomplete({
minlength:3,
delay: 500,
source: cat_data
});
}
});
uhm... i'm not sure, but i don't think that autocomplete has success property because its a property of an ajax call... maybe you use it inside an ajax call to get back the source, but in your case you already has surce providerdata, true?
Assuming that your $.map works fine, you can do something like:
var cat_data = $.map(providerdata, function(item) {
return {
value: item.NAME,
label: item.NAME,
}
});
$('#test').autocomplete({
source: cat_data,
minlength:3,
delay: 500,
});
[edit] - i see doc and i think you can do also:
$('#test').autocomplete({
source: function(){
return $.map(providerdata, function(item) {
return {
value: item.NAME,
label: item.NAME,
};
})
},
minlength:3,
delay: 500,
});
is it works?
I am trying to capture the text from a Kendo AutoComplete component and save it to a variable to later use in other components. The code is below and I have a link to the code at jsbin.com. Note: the code jsbin.com does not work for me in IE9, Firefox and Chrome work fine.
I attach my onSelect function fires when a selecton is made in the autoComplete control. I then assign the dataItem to my variable "selectedGeoname". I successfully write the object's text property to an element on screen and I use an alert to confirm that selectedGeoname is populated by the object.
However, when I later try to use the variable to pass the value to another component, the variable is null. I instantiate both components and declare the variable inside $(document)ready. I would have to believe that this is all ablout scope so perhaps one of you javascript wizards can help poor old .Net guy to fix this code.
Thanks,
Greg
HTML as follows:
<!DOCTYPE html>
<html>
<head>
<link href="http://cdn.kendostatic.com/2012.2.710/styles/kendo.common.min.css"
rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.2.710/styles/kendo.default.min.css"
rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.2.710/styles/kendo.dataviz.min.css"
rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.2.710/styles/kendo.mobile.all.min.css"
rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://cdn.kendostatic.com/2012.2.710/js/kendo.all.min.js"></script>
<title></title>
</head>
<body>
<p>
<label for="customer">Choose a customer:</label>
<input id="customer" />
<div id="result"></div>
</p>
<p>
<label for="stores">Choose a store:</label>
<input id="stores" />
</p>
<script type="text/javascript">
$(document).ready(function () {
$("#customer").kendoAutoComplete({
dataTextField: "name",
dataSource: {
serverFiltering: true,
transport: {
read: {
url: "http://ws.geonames.org/searchJSON",
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: function () {
return $("#customer").val();
}
}
}
},
schema: {
data: "geonames"
}
},
filter: "startswith",
placeholder: "Select Customer...",
height: 500,
suggest: true,
select: onSelect
});
var selectedGeoname;
function onSelect(e) {
var dataItem = this.dataItem(e.item.index());
selectedGeoname = dataItem;
//output
$("#result").html(selectedGeoname.name);
alert(selectedGeoname);
}
$("#stores").kendoDropDownList({
autoBind: false,
enable: true,
dataTextField: "StoreName",
dataValueField: "StoreId",
dataSource: {
serverFiltering: true,
transport: {
read: {
url: '#Url.Action("JsonGetStores", "Home")',
data: {
customer: selectedGeoname
}
}
}
}
});
});
</script>
</body>
</html>
You can use this code as your onSelect to achieve this:
function onSelect(e) {
selectedGeoname = this.value();
//output
$("#result").html(selectedGeoname.name);
alert(selectedGeoname);
}
When called from the context of the AutoComplete object this.value() can be used to get the value of the AC input element.
If you need to access the current value of the variable outside of the scope you can use this method: $("#customer").data("kendoAutoComplete").value().
Hope this helps!