Select2 search box - coffeescript

I have a formatting issue with the following feature. As you'll see below, it mostly works, just the formatting of the search box is not what I want (I want to replicate the typeahead Twitter Bootstrap feature):
A user can enter a book title in a search box, get a selection of books to chose from (through ajax) in the dropdown under the searchbox, and select a book. Upon selection of a book in the dropdown, a form is filled up with the book information. Just like so:
My problem is that select2 automatically changes the format of the search input (adds css around the selected item in search box). See here:
Question
I know it's not exactly what Select2 is meant to be used for, but I'd like to have the search box value to be "rails", appearing exactly the way it was when I typed it (first screenshot). How do I keep a regular input format?
Details:
Here is the coffeescript code I have so far (it features asynchronous loading of the pictures, and formatting of the selection):
jQuery ->
get_image = (unique_id, image_url) ->
img = $("<img />").load(->
$(".#{unique_id} .typeahead_photo_wrapper").html(img)
).error(->
$(".#{unique_id} .typeahead_photo_wrapper").html("No preview")
).addClass('typeahead_photo').attr({src: image_url}).fadeIn(500)
format_item = (book) ->
console.log book
itm = ''
itm += "<div class='typeahead_wrapper #{book.isbn}'>"
itm += "<div class='typeahead_photo_wrapper'>"
itm += "<div class='typeahead_photo'>...</div>"
itm += "</div>"
itm += "<div class='typeahead_labels'>"
itm += "<div class='typeahead_primary'>#{book.title}</div>"
itm += "<div class='typeahead_secondary'>#{book.author}</div>"
itm += "</div>"
itm += "</div>"
get_image(book.isbn, book.image)
itm
update_with_item = (item) ->
keywords = $("#learning_item_book_search").val()
# console.log item
$("#new-book #learning_item_unique_identifier").val(item.isbn)
$("#new-book #learning_item_source").val(item.source)
$("#new-book #learning_item_name").val(item.title)
$("#new-book #learning_item_description").val(item.description)
$("#new-book button").focus()
item.title
retrieve_books = (data) ->
books = []
$.each data, (i, item) ->
books.push(
id: item.id
isbn: item.isbn
title: item.title
author: item.authors
description: item.description
image: item.volume_info.imageLinks.smallThumbnail
)
books
$("#learning_item_book_search").select2({
minimumInputLength: 2
tags: true
ajax:
url: "/raw_items/fetch_books"
dataType: 'json'
quietMillis: 200
data: (term, page) ->
query: term
results: (data, page) ->
return {results: retrieve_books(data)}
maximumSelectionSize:1
formatResult: format_item
formatSelection: update_with_item
formatInputTooShort: (term, minLength) ->
"Searching book on Google books"
dropdownCssClass: 'typeahead'
})

you can put select2 into multiselect mode - which will make it look like the regular text field you want. use maximumSelectionSize:1 option to limit selection to a single item. use 'change' event on the original html control to populate the form.

In format_item add a line
$("#learning_item_book_search").select2('val', '')
For multiselect
$("#learning_item_book_search").select2('val', [])
It will keep the search term instead of adding the selected item.

Related

Ag-Grid: add a placeholder text in agSelectCellEditor dynamic dropdown options list

I am using Ag-Grid for displaying tabular data, is there a way we can add a placeholder in the dropdown options which are displayed in a column where we have an agSelectCellEditor?
Problem Statement:
Sample Code:
for(const [key,value] of countryCodes ) {
if (key !== ' ') {
countryNames.push([value.countriesCd]);
}
}
console.log(this.countryNames) = [['France'], ['Belgium'], ['USA'], ['UAE']]
For eg: The column filed = 'country'
country.cellEditor = 'agSelectCellEditor',
country.singleClickEdit = true,
country.cellEditorParams = {
values.countryNames,
}
When clicking on the country column, it shows the select dropdown with the countryNames list and without making any selection it defaults the dropdown to France, its confusing for the users as an option is displayed in the editorCell without selection

Get all bookmark IDs from Word Document

I want to scan an entire document containing text with the styles Heading 1, Heading 2, normal text and several bullet points / other text (which is basically a tech report). After scanning I want to extract bookmarks assigned to "Heading 2" elements, which also act as sub heading titles within the report.
getBookmarks() is defined in the Preview / Beta API which works if my cursor is placed on the "Heading 2" element, as seen below:
async function getBookmarks() {
Word.run(function(context) {
var range = context.document.getSelection();
var bkmrk = range.getBookmarks(true, true);
return context.sync().then(function() {
console.log("The bookmarks read from the document was: " + bkmrk.value);
});
}).catch(function(error) {
console.log("Error: " + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
}
I've managed to scan the entire document and obtain the "style" attribute as well, as seen from the example code on API documentation:
async function getParagraphAll() { await Word.run(async (context) => {
// Gets the complete sentence (as range) associated with the insertion point.
let paragraphs = context.document.body.paragraphs
paragraphs.load("text, style");
await context.sync();
// Expands the range to the end of the paragraph to get all the complete sentences.
let completeParagraph = paragraphs.items[0]
.getRange()
.expandTo(
context.document
.getSelection()
.paragraphs.getFirst()
.getRange("End")
)
paragraphs.load("text, style, hyperlink");
await context.sync();
for (let i = 0; i < paragraphs.items.length; i++) {
console.log(paragraphs.items[i].style);
//let range = paragraphs.items[i].getRange() - Why is this not working ?
//let bkmrk = range.getBookmarks(true, false) - This doesnt get me the bookmark while its in
//the loop scanning the entire document. Is it because it fails on "Normal" style?
// Should I filter out "Normal" and only run "getBookmarks" on "Heading" style ?
console.log(paragraphs.items[i].style);
} }); }
I've made the reference to Libraries available in the preview API link: https://appsforoffice.microsoft.com/lib/beta/hosted/office.js
I'm struggling to understand why I can get the bookmark at cursor level but when I want to get it for the entire document, it just displays
do context.sync() before loading any property. There is no need for
load.

Getting webpage elements by class using Keyboard Maestro

I frequently go to a library results page that has two pieces of information I want:
The Listing Title: An <h1> with class="title"
The Call Number: A <td> with class="call"
I want to be able to automatically copy the content of these two elements to a couple of named clipboards. Is this possible?
Awesome person, ComplexPoint, answered this on the KM forums here
(function (strPath) {
var r = document.evaluate(strPath, document, null, 0, null),
lst = [],
oNode;
while (oNode = r.iterateNext()) {
lst.push(oNode.className + ' = ' +oNode.textContent);
}
return lst.join('\n');
})("//h1[#class='title'] | //td[#class='call']")

jQuery Autocomplete id and item

I have a working query autocomplete code that completes the full_name when letters are typing. What I am trying to figure out is how to get the user_id for that goes with the full_name. I have JSON that comes back like so:
[{"full_name":"Matt","user_id":"2"},{"full_name":"Jack","user_id":"9"},{"full_name":"Ace","user_id":"10"},{"full_name":"tempaccount","user_id":"11"},{"full_name":"Garrett","user_id":"26"},{"full_name":"Joe","user_id":"29"},{"full_name":"Raptors","user_id":"32"}]
Below is my jQuery code. I am using PHPfox framework.
$(function(){
//attach autocomplete
$("#to").autocomplete({
//define callback to format results
source: function(req, add){
//pass request to server
//$.getJSON("friends.php?callback=?", req, function(data) {
$.ajaxCall('phpfoxsamplee.auto', 'startsWith='+req.term)
.done(function( data ) {
//create array for response objects
var suggestions = [];
var data = $.parseJSON(data);
//process response
$.each(data, function(i, val){
//suggestions.push(val.full_name,val.user_id); (This works and shows both the full name and id in the dropdown. I want the name to be visible and the ID to goto a hidden input field)
suggestions.push({
id: val.user_id,
name: val.full_name
});
});
//pass array to callback
add(suggestions);
});
},
//define select handler
select: function(e, ui) {
//create formatted friend
alert(ui.item.full_name); //Trying to view the full_name (doesn't work)
alert(ui.item.id); // trying to view the id (doesn't work)
var friend = ui.item.full_name, (doesn't work)
//var friend = ui.item.value, (This works if I do not try to push labels with values)
span = $("<span>").text(friend),
a = $("<a>").addClass("remove").attr({
href: "javascript:",
title: "Remove " + friend
}).text("x").appendTo(span);
//add friend to friend div
span.insertBefore("#to");
$("#to").attr("disabled",true);
$("#to").attr('name','test').attr('value', 'yes');
$("#to").hide();
},
//define select handler
change: function() {
//prevent 'to' field being updated and correct position
$("#to").val("").css("top", 2);
}
});
//add click handler to friends div
$("#friends").click(function(){
//focus 'to' field
$("#to").focus();
});
//add live handler for clicks on remove links
$(".remove", document.getElementById("friends")).live("click", function(){
//remove current friend
$(this).parent().remove();
$("#to").removeAttr("disabled");
$("#to").show();
//correct 'to' field position
if($("#friends span").length === 0) {
$("#to").css("top", 0);
}
});
});
HTML
<div id=friends class=ui-help-clearfix>
<input id='to' type=text name='player[" . $num . "][name]'></input>
</div>
Consider the JQuery Autocomplete Combobox. It is not a standard widget, but you can pretty much paste their source. And it will enable you to capture values corresponding to text selections.

jQuery show div if value > x

I've been reading lots of topics about jQuery and showing div's, but I haven't found the answer to my specific question yet. Here's the thing:
Based on my value I want to show either div A or div B. The select field is filled with 20 countries, of which 19 get the same div (B) and only one get's another div (A). The one that get's div A has "value=1", so I figured to apply a "if select value > 1, show div B" principle. However, I can't manage to get it working. My other select-show-div mechanism was based on the exact value (I've posted it below), but this if-else thing makes me going crazy.
Any help would be appreciated!
My old value=exact code:
$('.div').hide();
$('#country').change(function() {
$('.div').hide();
$('#country' + $(this).val()).show();
});
});
And the corresponding HTML:
<div id="country1" class="div">
BLABLA
</div>
<div id="country2" class="div">
BLABLA
</div>
etc
I don't understand if you have a select menu, or divs. A possible solution could be the following:
$('select').change(function() {
var countryVal = $("select option:selected").val(); //get the value of the selected
$("#country1, #country2").hide(); //hide country divs, of previous selection
if(countryVal == 1) {$("#country1").show();} else {$("#country2").show()}; //if countryVal is 1 (the diffrent value) show the div #country1 else show the div #country2
});
updated Demo: http://jsfiddle.net/YnYxD/1
If I understood correctly, all the others countries have a value > 1, so you can't simply use the value to generate the id. The id must be 1 if the value is 1 and 2 otherwise.
Try :
$('#country').change(function() {
$('.div').hide();
var id = $(this).val() == 1 ? 1 : 2;
$('#country' + id).show();
});
});