Dropdown list is bottom of the site - javascript

I have a little problem with my select2 display.
The request work perfectly, I've got the right items, the problem is not here, the problem is the list is completely bottom of the site (after the footer).
the code is :
<input type="hidden" class="select2 form-control" id="select2" placeholder="search ..." name="q" value="{{ searchTerm ?: '' }}">
and :
<script type="text/javascript">
function format(product) {
return '<img src="/media/images/'+product.image+'" alt="" class="imgmedia-object" height="60" width="60"/><h5>'+product.name</h5><hr>';
}
$(document).ready(function() {
// Get this orders sku
var skus = [];
$('.sku').each(function(){
skus.push($(this).text().trim());
});
$(".select2").select2({
multiple: true,
minimumInputLength: 2,
tokenSeparators: [',', ' '],
ajax: {
url: "{{ url('sylius_backend_product_find') }}",
dataType: 'json',
data: function (term, page) {
return {
criteria: {
sku: term
}
};
},
results: function (data, page) {
return {
results: data
};
}
},
formatResult: format
}).on("select2-selecting", function(e) {
window.location = e.choice.url;
});
});
</script>
And I have a warning when I search terms :
This site appears to use a scroll-linked positioning effect. This may not work well with asynchronous panning; see https://developer.mozilla.org/docs/Mozilla/Performance/ScrollLinkedEffects for further details and to join the discussion on related tools and features!
The problem probably come from the warning, but I don't know how to solve it.
Thx in advance

It was simply because I didn't add the 'bundles/syliusweb/css/select2.css' line ...

Related

Semantic ui search not work

I work with semantic ui and when I do a search on a website the result is empty but when I look at my console I see the json result
this is my js code
$('.ui.search').search({
apiSettings: {
url: "https://api.github.com/search/repositories?q={query}"
},
fields: {
results: 'items',
title: 'name',
url: 'html_url',
description: 'description'
}
});
and my html code
<div class="ui right aligned category search item">
<div class="ui transparent icon input">
<input class="prompt" placeholder="Rechercher" type="text">
<i class="search link icon"></i>
</div>
<div class="results"></div>
</div>
screenshot results in my html page
and i have try the exemple for semantic-ui page
$('.ui.search')
.search({
type : 'category',
minCharacters : 3,
apiSettings : {
onResponse: function(githubResponse) {
var
response = {
results : {}
}
;
// translate GitHub API response to work with search
$.each(githubResponse.items, function(index, item) {
var
language = item.language || 'Unknown',
maxResults = 8
;
if(index >= maxResults) {
return false;
}
// create new language category
if(response.results[language] === undefined) {
response.results[language] = {
name : language,
results : []
};
}
// add result to category
response.results[language].results.push({
title : item.name,
description : item.description,
url : item.html_url
});
});
return response;
},
url: '//api.github.com/search/repositories?q={query}'
}
})
and this is not work
have the same problem as you
debugger and get this:
debug screenshot
it seems will get 'results' field from response, so if your response without 'results' field you need set 'results' in onResponse callback:
apiSettings : {
onResponse (response) {
return {
results: response.myresults
}
}
}
and if you didn't set the templates, it will use the standard template, standard template use 'title' field to show, you need do some transform like this:
response.myresults.forEach((item) => {
item.title = item.name;
})
hope this can help you

Populate text field from JsTree selection

I am trying to figure out a way to pass the selection from JSTree to a basic HTML form. (Which is then used by Flask & Wtforms). I've been able to pass it to the console log but then am not sure how to bring this back to the form.
Relatively new to JS so take it easy on me, but I am stumped on how to do this.
<label for="folderpath">Folder Path:</label>
<input type="text" id="folderpath" name="folderpath" value="">
<br>
<div id="container"></div>
<script id="jstree1" name="jstree1">
$('#container').jstree({
'core': {
"themes": {
"name": "default",
"dots": true,
"icons": true
},
'data': {
'url': "static/JSONData.json",
'type': 'GET',
'dataType': 'JSON',
}
}
});var folderpath =
$('#container').on("changed.jstree", function (e, data) {
console.log(data.instance.get_selected(true)[0].text);
});
</script>
EDIT
I tried using #folderout. But it would not work when using an input type="text" tag.
<label for="folderout">Folder Path</label>
<input type="text" name="folderout" class="form-control" id="folderout" >
$("#container").on("select_node.jstree", function (evt, data) {
var number = data.node.text
$('#folderout').html(number);
<label for="folderout">Folder Path</label>
<input type="text" name="folderout" class="form-control" id="folderout" >
<script id="jstree1" name="jstree1">
$('#container').jstree({
'core': {
"themes": {
"name": "default"
, "dots": true
, "icons": true
}
, 'data': {
'url': "static/JSONData.json"
, 'type': 'GET'
, 'dataType': 'JSON'
}
}
});
{ /* --- THIS IS FOLDER SELECTOR FOR ID "folderout" --- */
$("#container").on("select_node.jstree", function (evt, data) {
var number = data.node.text
document.getElementById("folderout").value = number; });};
</script>
The last part here did the trick. Converting the data.node.text to a variable. Then bringing the variable into html with getElementById. Now when you click a node it will populate that text field.

How to get Select2 to update a ajax call when country value is changed

I can't seem to find an easy example of how to update the states list when the country list has changed. All examples I've seen to be using all sorts of bits and peices that work depending on version and who is giving the solution.
Can someone help me how this can be easily done without ugly hacks. I've tried this so far and whilst it works, if I change the drop down for the second time, the new values just get appended to the old ones instead of replacing them. I've tried destroying and rebuilding but old values remain.
The data coming back from the server is valid json with id and text values. So far I've had no luck in getting the state list to update with new country state values when the country is changed
<select id="country" name="country" class="form-control" data-placeholder="Select...">
<optgroup label="Country">
<option></option>
<option value="US" > United States</option>
<option value="AU" > Austrailia</option>
</optgroup>
</select>
<select id="state" name="state" class="form-control" data-placeholder="Select...">
<optgroup label="State">
<option></option>
</optgroup>
</select>
$("#country").select2().on("change", function(e) {
var country = e.val;
$.post("states", {
country_id: country
}, function(e) {
if (e)
$("#states").select2({
data: e
});
})
});
$("#state").select2();
These are the values sent back from server
[{ id: 'ALB', text: 'ALABAMA' }, { id: 'ALS', text: 'ALASKA' }, { id: 'ARI', text: 'ARIZONA' }]
You have to remove the <option> tags from the select before setting the new data:
$.post("states", {
country_id: country
}, function(e) {
if (e){
$("#states option").remove();
$("#states").select2({
data: e
});
}
})
You may want to refine my example to avoid removing placeholders, if any.
See also this JSFiddle: https://jsfiddle.net/drj84go5/
The best option is to have an input (text) not a select2 and then convert it through select2 function using ajax.
Input:
<input type="text" id="states">
Javascript:
$('#states').select2({
placeholder: "States...", // placeholder
allowClear: true,
minimumInputLength: 0,
dropdownCssClass: "bigdrop",
width: '100%',
ajax: {
quietMillis: 2500,
url: "/Search/_SearchStates", // Server-side action
dataType: 'json',
data: function (term, page) {
return {
Text: term, // Text to search for
CountryId: $("#country").val(), // CountryId from #countries
};
},
results: function (data, page) {
return { results: data };
},
},
formatResult: function (item) {
return item.StateName; // Table name/description
},
id: function (element) {
return element.StateId; // Table id/code
},
formatSelection: function (item) {
return item.StateName; // Table name/description
}
});
You need to have a server-side action that will give you the list of states.
To get the StateId you need to do:
$("#states").select2('val');

Allowing select2 jquery ajax in tag mode to repeat tags

I am using select2-jquery to bring several items from the server (ajax) and the allow the user to select several of them, it works fine but I cannot select any given tag more than once and that's a requirement I'll paste some of my code, hopefully it helps. I have inspected the ajax requests and i can see the same data getting back from the server under the same search terms, but once an item is selected the select2 does NOT displays it anymore
This is a part of my View:
<div class="form-group">
#Html.LabelFor(m => m.Vals, T("Values"), new { #class = "control-label col-md-2" })
<div class="col-md-7">
<input id="Values" name="Values" type="hidden" style="width: 100%" data-url="#Url.Action("Action", "Controller")" />
</div>
</div>
And this is the JS part:
$(function () {
var fullTemplateString = 'some template string';
var resultTemplateString = 'other template';
var $selectInput = $('#Values');
initilizeSelect2($selectInput, fullTemplateString, resultTemplateString);
});
function initilizeSelect2($selectInput, fullTemplate, resultTemplate) {
$selectInput.select2({
placeholder: "Select Labs",
minimumInputLength: 2,
multiple: true,
tokenSeparators: [","],
tags: false,
ajax: {
url: $selectInput.data('url'),
dataType: 'json',
quietMillis: 250,
data: function(term, page) {
return {
term: term,
};
},
results: function(data, page) {
return {
results: data
};
}
},
formatSelection: function (item) {
return format(item, resultTemplate);
},
formatResult: function (item) {
return format(item, fullTemplate);
},
escapeMarkup: function (m) { return m; }
});
}
function format(item, templateString) {
var result = templateString
.replace(/\^\^id\^\^/g, item.id)
.replace(/\^\^icon\^\^/g, item.icon)
.replace(/\^\^text\^\^/g, item.name)
.replace(/\^\^desc\^\^/g, item.desc);
return result;
}
I am using select2 version:3.4.5 extensively in this project so any changes in this regard would be very painful
Thanks in advance
after a lot of search and debugging through the select2 code i found a way (hack) to pull this out by removing the css class .select2-selected that prevents already selected elements from displaying again. I know this isn't the best solution there is, but it is working now. I really welcome any improvements or better solutions

Event default not triggering in jQuery module

I'm attempting to write a jQuery script to store an authentication token from a REST API service. I had a block of working code but decided to modularize to make the application more scalable. Now, it seems that the preventDefault portion is no longer working.
<form action="/" id="authorize">
<label for="username">Username:</label><br />
<input type="text" id="username" required /><br />
<label for="password">Password:</label><br />
<input type="password" id="password" required /><br />
<input type="submit" value="Authorize" /><span id="isValid" class="checkContainer"> </span>
</form><hr />
<label for="serviceType" class="fieldDisabled">Method: </label>
<select id="serviceType" disabled>
<option></option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
The script is saved separately as authorize.js and invoked in the module as follows:
<script src="js/authorize.js"></script>
<script>
$(document).ready(function() {
Authorize.init();
});
</script>
Here's the module itself:
var s;
var Authorize = {
token: null,
settings: {
username: $("#username"),
password: $("#password"),
form: $("#authorize"),
validationIcon: $("#isValid"),
selector: $("#serviceType"),
selectorLabel: $("label[for='serviceType']"),
serviceSelector: $(".methodFieldDisabled"),
url: "redacted"
},
init: function() {
s = Authorize.settings;
this.bindUIActions();
},
bindUIActions: function() {
s.form.submit(function(event) {
event.preventDefault();
data = Authorize.buildJSON(s.username.val(), s.password.val());
Authorize.getToken(json);
});
},
buildJSON: function(username, password) {
var data = {};
data['grant_type'] = password;
data['username'] = username;
data['password'] = password;
return data;
},
getToken: function(data) {
$.ajax({
type: "POST",
url: s.url,
data: data,
success: function(json) {
Authorize.success(json);
},
error: function(json) {
Authorize.error(json);
}
});
},
success: function(json) {
Authorize.token = json.accessToken;
Authorize.revealServiceSelector();
},
error: function(json) {
Authorize.hideServiceSelector();
},
revealServiceSelector: function() {
s.serviceSelector.hide();
if(s.validationIcon.hasClass("invalid")) {
s.validationIcon.removeClass("invalid");
}
selectorLabel.removeClass("fieldDisabled");
selector.prop("disabled", false);
s.validationIcon.addClass("valid");
},
hideServiceSelector: function() {
s.serviceSelector.hide();
if(s.validationIcon.hasClass("valid")) {
s.validationIcon.removeClass("valid");
}
selectorLabel.addClass("fieldDisabled");
selector.prop("disabled", "disabled");
s.validationIcon.addClass("invalid");
}
};
I've been toiling over this for about a day now and can't seem to locate the point of failure. When the form is submitted, it redirects to the root directory of the server instead of executing the script as intended.
Just a few typos which stopped the code in its tracks. The submission was the default behavior as your code failed to complete.
Use a debugger to see the errors at runtime (get to know and love your F12 debugging tools in Chrome etc!):
1) You have the wrong variable (json instead of data) on the line below so you get an error:
bindUIActions: function () {
s.form.submit(function (event) {
event.preventDefault();
data = Authorize.buildJSON(s.username.val(), s.password.val());
Authorize.getToken(data); // <<<<<<<<<<<<<<<<<<<<<<<
});
2) You also failed to put your scope (s) on a couple of variables:
revealServiceSelector: function () {
s.serviceSelector.hide();
if (s.validationIcon.hasClass("invalid")) {
s.validationIcon.removeClass("invalid");
}
s.selectorLabel.removeClass("fieldDisabled");
s.selector.prop("disabled", false);
s.validationIcon.addClass("valid");
},
hideServiceSelector: function () {
s.serviceSelector.hide();
if (s.validationIcon.hasClass("valid")) {
s.validationIcon.removeClass("valid");
}
s.selectorLabel.addClass("fieldDisabled");
s.selector.prop("disabled", "disabled");
s.validationIcon.addClass("invalid");
}
Your from action is pointed to "\" which is the root of your directory. Instead point it to the file that contains the code you want to fire.

Categories