I would like to get the row id of selected item in my autocomplete function, I get the values of my source from a php variable.
<script>
$(function() {
var availableTags = [ <? php echo($toto); ?> ];
$("#foo").autocomplete({
source: availableTags
});
});
</script>
I already tried this function but it does not seem to work. In fact, when I add it to my script, my autocomplete won't work anymore.
<script>
$(function () {
var availableTags = [ <? php echo($ListeNomsFormateeFinale); ?> ];
$("#nomClient").autocomplete({
source: availableTags
select: function (event, ui) {
$("#textfield1").val(ui.item.label); // display the selected text
$("#textfield2").val(ui.item.value); // display selected id
return false;
}
});
});
</script>
What am I doing wrong here? and is there a quick fix to this problem?
Edit:
I actualy needed to add a comma after source: availableTags, I also deleted the return false. but it dosen't return the id of the selected row, it actually writes the same value in the two textfields textfield1 and textfield2
From : Api Jquery UI - Autocomplete - option source
Array: An array can be used for local data. There are two supported formats:
An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.
The second point (2.) give a way to store the "id" (or something else) of the selected object. By example :
var yourSource = [ { label: "Choice1", id: "id1" } ];
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<form>
<input type="text" id="fooInput" />
</form>
<div id="result">
</div>
<script type="text/javascript">
var yourSource = [
{
label: "A",
id: "id1"
},
{
label: "B",
id: "id2"
}];
$("#fooInput").autocomplete({
source: yourSource,
select: function(event, ui) {
var e = ui.item;
var result = "<p>label : " + e.label + " - id : " + e.id + "</p>";
$("#result").append(result);
}
});
</script>
So try to format your data source like this :
var source = [ {label:"Foo", id:"1"}, ... ];
Related
I have a user search that autocompletes by both ticker and name. The search results come back as "{{ticker}} - {{name}}". When a result is selected, I want it to fill with only the ticker, where as it currently fills with "{{ticker}} - {{name}}".
Here is my python code:
if 'term' in request.GET:
tickers = Company.objects.filter(ticker__istartswith = request.GET.get('term')) | Company.objects.filter(name__istartswith = request.GET.get('term'))
companies = []
for ticker in tickers:
companyTicker = ticker.ticker + " - " + ticker.name
companies.append(companyTicker)
return JsonResponse(companies, safe=False)
and here is my javascript:
<script>
$( function() {
$( "#ticker3" ).autocomplete({
source: '{% url "financials:get_financials" %}',
select: function (event, ui) {
ticker.ticker
}
});
} );
</script>
Any help greatly appreciated!
A quick look at the jquery autocomplete docs reveals that you can use an array of objects for your source option. Each object should have a label and value attribute. The following should get you what you need.
if 'term' in request.GET:
tickers = Company.objects.filter(ticker__istartswith = request.GET.get('term')) | Company.objects.filter(name__istartswith = request.GET.get('term'))
companies = []
for ticker in tickers:
label = f"{ticker.ticker} - {ticker.name}"
companyTicker = {'label': label, 'value': ticker.ticker}
companies.append(companyTicker)
return JsonResponse(companies, safe=False)
You can then remove the select option in your javascript:
<script>
$(function () {
$("#ticker3").autocomplete({
source: '{% url "financials:get_financials" %}',
});
});
</script>
I have two arrays that I had already successfully used to make a table in JavaScript. Now, I would like to make the table a jQuery DataTable because of its UI features. I thought I had the correct way of creating one, but I get an error.
This is also within a Flask app, if that makes a difference
Code
<body>
<!-- Load jQuery -->
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin = "anonymous"></script>
<!-- jQuery dataTables script-->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<!-- If that fails, we have a backup in our directory-->
<script type = text/javascript src = "{{
url_for('static', filename = 'jquery.js') }}"></script>
<script type = text/javascript src = "{{
url_for('static', filename = 'jQuery.dataTables.min.js') }}"></script>
<!-- Form for submitting our NBA Data-->
<form id = "nameForm" role = "form">
<!-- Input box so we can search by player name -->
<input name = "text" type = "text" id = "searchBox">
<!-- Button that we will use to make the actual ajax call -->
<button id = "searchBtn"> Search </button>
</form>
<!-- Container that we will add our data table to later -->
<table id = "myTable" class = "display" width = "25%"></table>
<!-- Script for the button click action -->
<script type = text/javascript>
//Root stuff
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
var dataList;
var titles;
var dtColumns;
//Root so we can get the data from our form
$('button#searchBtn').click(function(e) {
//Prevent our form from submitting, which is its default action/purpose
e.preventDefault();
//Get the data from our function in the Flask App
$.getJSON($SCRIPT_ROOT + '/_get_data', {
//Our searchName variable will be the one from our HTML input box
searchName: $('input[name = "text"]').val(),
}, function(data) {
dataList = data.dataList;
titles = data.headers;
dtColumns = [];
for (var i = 0; i < titles.length; i++) {
dtColumns.push({ title : titles[i] });
}
});
});
//When our page is fully loaded, convert the table to a jQuery data table
$(document).ready(function () {
$('#myTable').DataTable( {
data: dataList,
columns: dtColumns
});
})
</script>
</body>
EDIT: The arrays that I am working with, and the newest errors
dtColums is
["Player", "Pos", "Age", "Tm", "G", "GS", "MP", "FG", "FGA", "FG%", "3P", "3PA", "3P%", "2P", "2PA", "2P%", "eFG%", "FT", "FTA", "FT%", "ORB", "DRB", "TRB", "AST", "STL", "BLK", "TOV", "PF", "PTS"]
And dataList is
["James Harden", "SG", "30", "HOU", "7", "7", "35.3", "9.1", "24.0", ".381", "3.4", "13.6", ".253", "5.7", "10.4", ".548", ".452", "14.9", "16.1", ".920", "1.4", "3.7", "5.1", "7.4", "1.0", "0.4", "5.7", "3.6", "36.6"]
Current errors that are being returned in a alert in my browser window:
DataTables warning: table id=myTable - Requested unknown parameter '12' for row 0, column 12. For more information about this error, please see http://datatables.net/tn/4
DataTables warning: table id=myTable - Requested unknown parameter '1' for row 4, column 1. For more information about this error, please see http://datatables.net/tn/4
You are making an async call but not waiting it to return before initializing DataTable. Basically, you are trying to create dataTable from a variable that has not the values you need. You can try to initialize table within callback of getJSON function.
I have not used DataTables for a long time and as I remember I have always written the data to table before initializing but you can try this;
<script type = text/javascript>
//Root stuff
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
var dataList;
var titles;
var dtColumns;
//Root so we can get the data from our form
$('button#searchBtn').click(function(e) {
//Prevent our form from submitting, which is its default action/purpose
e.preventDefault();
//Get the data from our function in the Flask App
$.getJSON($SCRIPT_ROOT + '/_get_data', {
//Our searchName variable will be the one from our HTML input box
searchName: $('input[name = "text"]').val(),
}, function(data) {
dataList = data.dataList;
titles = data.headers;
dtColumns = [];
for (var i = 0; i < titles.length; i++) {
dtColumns.push({ title : titles[0] });
}
$('#myTable').DataTable( {
data: dataList,
columns: dtColumns
});
});
});
</script>
I am trying to get data stored in attributes of dynamically created elements that have been added to the DOM.
When a button is clicked, an AJAX call is made which returns a collection of objects. Using Javascript/JQuery, I am then adding new HTML elements for each of these returned objects, and adding their property values to attributes on the element. I am then adding a click listener to each of these dynamically created elements. When clicked I want to get the value in these attributes.
At the moment the id value is present, but the value of name is undefined.
For example, given the following HTML:
<input type="button" id="button" value="Get objects" />
<div id="objects-wrapper"></div>
Json response from server:
[
{
"id": 16,
"name": "eeeee",
},
{
"id": 17,
"name": "MIT Top New"
}
]
$(document).ready(function() {
$('#button').click(function() {
var id = $(this).attr('id');
var posting = $.post('/get/objects', {
id: id
});
posting.done(function(data) {
var objectsWrapper = $('#objects-wrapper');
objectsWrapper.empty();
if (data.length == 0) {
$(objectsWrapper).html('No objects found...');
} else {
$(objectsWrapper).empty();
for (i = 0; i < data.length; i++) {
var object = $('<div class="object">' + data[i].name + '</div>').on('click', function() {
var objectId = $(this).attr('id'); // <-- is present
var name = $(this).attr('name'); // <-- undefined
// do something with name
});
objectsWrapper.append(object);
}
}
});
return false;
});
});
The name value is present and is being used as the anchor text. Which I have verified as the following markup:
MIT Top New
How do I correctly get at the attribute name of the dynamically created anchor element?
You can use .find() of jQuery to find for the elements with selector in the DOM and make it work
Here is an example with your data.
var data = [
{
"id": 16,
"name": "eeeee",
},
{
"id": 17,
"name": "MIT Top New"
}
];
data.forEach(e=>{
$("#objects-wrapper").append(` </br> ${e.name} </br>`)
});
$("#button").click(function(){
$("#objects-wrapper").find("a").each(function(){
console.log($(this).attr("name"))
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="button" id="button" value="Get objects" />
<div id="objects-wrapper"></div>
By the way in your code, why you need to get it from DOM ? you're assigning the name yourself why not use it ? data[i].name this is the name right. Use it instead of getting from the DOM again
I want to display only parts of a .json that I scraped with scrapy.
the scrapy output looks something like this and has about 500 entries:
data.json
[
{
"Content":["<h2>Heading of Paragraph1</h2><p>the actual pargraph1</p>"],
"Titel": ["Heading of Paragraph1"]
}
,
{
"Content": ["<h2>Heading of Paragraph2</h2><p>the actual pargraph2</p>"],
"Titel": ["Heading of Paragraph2"]
}
,
{
"Content": ["<h2>Heading of Paragraph3</h2><p>the actual pargraph3</p>"],
"Titel": ["Heading of Paragraph3"]
}
]
What I want to do is to generate a list of All the "Titel" elements for the user to choose from. Then the website should display the chosen paragraphs.
I figured out that some javascript are probably the way to go. I plan to use chosen later to make the UI usable.
So far I came up with this html
index.html
<body>
<form action="/returnselected_paragraphs.js">
<select name="pargraphs" multiple>
<option value="Heading of Pargraph1">Heading of Paragraph1</option>
<option value="Heading of Pargraph2">Heading of Paragraph2</option>
<option value="Heading of Pargraph3">Heading of Paragraph3</option>
<!-- this should be genereated by javascript with data from the json --!>
<input type="submit">
</form>
<h1>output</h1>
<h2>Heading of Paragraph1</h2><p>the actual pargraph1</p>
<h2>Heading of Paragraph2</h2><p>the actual pargraph2</p>
<!-- this should be genereated by javascript with data from json--!>
My problem is the javascript.
I found this code on jsfiddle which seems similar to what I want, but the data is formated differently. I don't know how to adapt it to my data.
I put my idea here: https://jsfiddle.net/jtxzerpu/
Thank you all for your time, I hope I did stick to all the rules.
Try this
Iterate the array and create select
Bind change event on select on which content should be rendered.
Demo
var arr = [{
"Content": ["<h2>Heading of Paragraph1</h2><p>the actual pargraph1</p>"],
"Titel": ["Heading of Paragraph1"]
},
{
"Content": ["<h2>Heading of Paragraph2</h2><p>the actual pargraph2</p>"],
"Titel": ["Heading of Paragraph2"]
}, {
"Content": ["<h2>Heading of Paragraph3</h2><p>the actual pargraph3</p>"],
"Titel": ["Heading of Paragraph3"]
}
];
//prepare the options first
var options = arr.map( function( item ){
return "<option value='" + item.Titel[0] + "'>"+ item.Titel[0] + "</option>"
} ).join( "" );
//set all the options to select and then bind change event
$( "select" ).html( options ).change( function(){
$( "#paraContent" ).html( "" );
var val = $(this).val();
$( "#paraContent" ).html( val.map( function( title ){
return arr.find( (s) => s.Titel[0] == title ).Content[0];
}).join( "</br>" ) )
//console.log(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/returnselected_paragraphs.js">
<select name="pargraphs" multiple>
</select>
<p id="paraContent">
</p>
<input type="submit">
</form>
You can build the options list easily:
const options = json_data.reduce(
function (fragment, item)
{
const option = document.createElement("option");
option.value = item.Titel[0];
option.textContent = option.value;
fragment.appendChild(option);
return fragment;
},
document.createDocumentFragment()
);
Then append the options to your select (the document fragment will "merge" with the select and disappear, don't worry).
From your reference on jsfiddle, you can modify that to the code below:
var data = [
{
"Content":["<h2>Heading of Paragraph1</h2><p>the actual pargraph1</p>"],
"Titel": ["Heading of Paragraph1"]
}
,
{
"Content": ["<h2>Heading of Paragraph2</h2><p>the actual pargraph2</p>"],
"Titel": ["Heading of Paragraph2"]
}
,
{
"Content": ["<h2>Heading of Paragraph3</h2><p>the actual
pargraph3</p>"],
"Titel": ["Heading of Paragraph3"]
}
]
$.each(data, function () {
var $option = $('<option/>').text(this.Titel[0]).val(this.Titel[0]);
$option.data("content",this.Content[0])
$('#selectCompany').append($option);
});
Here is the link to your modified code in action:
https://jsfiddle.net/azqxhjgx/
You can use click event on option to display the content of the object where you want, something like this:
$("#selected > option").click(function(){
// do whatever with $this.data("content")
})
I am writing a dropdown list in the Kendo Editor custom tools that needs to show smart tag values to be placed into the textarea. My javascript code looks like this:
$("#editor").kendoEditor({
resizable: {
content: true,
toolbar: true
},
tools: [
{
name: "insertHtml",
items: [
{ text: "TEXT", value: "VALUE" },
{ text: "TEXT", value: "VALUE" }
]
}
],
messages: {
insertHtml: "Placeholders"
}
});
I have an XML file with all the values that need to be populated.
<SMARTTAGS>
<TAG>
<TEXT>Login Link</TEXT>
<VALUE>[FASTSIGNLINK]</VALUE>
</TAG>
<TAG>
<TEXT>Enrollment Registration Link</TEXT>
<VALUE>[SIGNLINK]</VALUE>
</TAG>
<TAG>
<TEXT>Onboarding Login Link</TEXT>
<VALUE>[OBLINK]</VALUE>
</TAG>
How can i get these values into my javascript items (in the TEXT and VALUE areas) so that all i have to do is update the xml file if i want to add / remove text/values?
I think you could try something like that.
tags = document.getElementsByTagName('SMARTTAGS')[0].getElementsByTagName('TAG');
var arr = [];
for (var i = 0,c=tags.length; i<c; i++) {
arr.push({
text: tags[i].getElementsByTagName("TEXT")[0].childNodes[0].nodeValue,
value: tags[i].getElementsByTagName("VALUE")[0].childNodes[0].nodeValue
});
}
I dont know if it is the best way to solve your problem.
If you want to load the xml from somewhere else, you can just use parseXML:
var xmlDoc = $.parseXML( "<SMARTTAGS><TAG><TEXT>Login Link</TEXT><VALUE>[FASTSIGNLINK]</VALUE></TAG><TAG><TEXT>Enrollment Registration Link</TEXT><VALUE>[SIGNLINK]</VALUE></TAG><TAG><TEXT>Onboarding Login Link</TEXT><VALUE>[OBLINK]</VALUE></TAG></SMARTTAGS>" );
var xml = $( xmlDoc );
var tags = xml.find("TAG");
var items = [];
for(var i = 0; i < tags.length; i++){
var tag = $(tags[i]);
items.push({
text: tag.find("TEXT")[0].innerHTML, value: tag.find("VALUE")[0].innerHTML
})
}