How do I make a newly created select2 tag persists after the option is no longer selected - jquery-select2

I want to be able to have the option persist after I added a tag. A similar question was solved here:
Dynamically add item to jQuery Select2 control that uses AJAX
But a commenter is right, it is only solved with an additional input box somewhere not in the original select box.
[![Question kinda solved][1]][1]
I tried a number of things and they all do not work:
returning an object with createOption or createSearchChoice
Appending a new Option
This is because the widget already secretly adds a new options as is necessary to accommodate the new tag, but if it wasn't a tag from the original data, it will delete it if a new option is selected. I thought maybe on the select2:select event, I could see if the new value is in the data somewhere. Alas, that data is hard to find.
[1]: https://i.stack.imgur.com/CyCC4.png
Here are some failed attempts with commentary
var quote = {};
google.script.run.withSuccessHandler(function(e){
quote = $('#quote').select2({
width:'100%',
data: e, //[{id:'quote', text:'quote'},{id:'quote2', text:'quote2'}]
tags: true,
/*Alas, this doesn't work either becuse the tag is still in the option when we check fo rit
createTag: function(){
if (quote.find("option[value='" + params.term + "']").length) quote.append(Option(params.term,params,term,true,true)).trigger('change')
return {id: params.term, text:params.term})
*/
//insertTag: function(d,t){d.push(t)} Didn't work either
allowClear:true,
placeholder:'No Quote'
}).on('select2:select',function(e){
/*
// Set the value, creating a new option if necessary
This doesn't work because the new item is in the option thingy temporarily while we're trying to see if its there
if (quote.find("option[value='" + e.params.data.id + "']").length) {
quote.val(e.params.data.id).trigger('change');
} else {
// Create a DOM Option and pre-select by default
var newOption = new Option(e.params.data.id, e.params.data.id, true, true);
// Append it to the select
quote.append(newOption).trigger('change');
}
*/
if (e.params.data.id&&(quotes.indexOf(e.params.data.id)!=-1)){
loadQuote(e.params.data.id)
} else {
//new quote so now we have to make preparations...
quotes.push(e.params.data.id)
console.log(e.params.data)
console.log(quotes)
var newOption = new Option(e.params.data.id,e.params.data.id,true,true)
quote.append(newOption).trigger('change')
//don't send anything to the server, because there is no need
}
})
quote.val(null).trigger('change')

Related

Problems with js in Rails

My JS work only if i reload page.
Description my problems
1.I have book
2.Book have description
3.In action show i have logic for present description
Logic:
1. If description.length > 250 i show 250 symbols and show view_more button
2. If user click on button then my js must work
4.When i on books#index => choose some book(#show)=> now i on book_page and i see view_button => when i click => nothing was happen
5. But if i reload page before click on button => my js work fine
My js
(function(window, document, undefined){
window.onload = init;
function init(){
let btn_view_more = document.getElementById('button_for_view_more')
let description_all = document.getElementById('book_description_all')
let description_short = document.getElementById('book_description_short')
btn_view_more.addEventListener('click', ()=>{
description_all.classList.remove('hide_description')
description_short.style.display = 'none'
});
};
})(window, document, undefined);
But i have new version of my js
document.addEventListener("turbolinks:load", function() {
myFunc();
})
function myFunc(){
let btn_view_more = document.getElementById('button_for_view_more')
let description_all = document.getElementById('book_description_all')
let description_short = document.getElementById('book_description_short')
btn_view_more.addEventListener('click', ()=>{
description_all.classList.remove('hide_description')
description_short.style.display = 'none'
});
}
New version work fine even i don't reload page, but i have error in my console
Cannot read properties of null (reading 'addEventListener') (can't find id button_for_view_more)
What i want:
1. Js work even i don't reload page
2. Zero error in console
My solution is connect js only to the page where it is used, delete from javascript/some.js and drop require from pack/application.js. You can also add a condition to your script that will check whether such an ID is currently on the page. And only after run the main block.

Select2 AJAX doesn't update when changed programatically

I have a Select2 that fetches its data remotely, but I would also like to set its value programatically. When trying to change it programatically, it updates the value of the select, and Select2 notices the change, but it doesn't update its label.
https://jsfiddle.net/Glutnix/ut6xLnuq/
$('#set-email-manually').click(function(e) {
e.preventDefault();
// THIS DOESN'T WORK PROPERLY!?
$('#user-email-address') // Select2 select box
.empty()
.append('<option selected value="test#test.com">test#test.com</option>');
$('#user-email-address').trigger('change');
});
I've tried a lot of different things, but I can't get it going. I suspect it might be a bug, so have filed an issue on the project.
reading the docs I think maybe you are setting the options in the wrong way, you may use
data: {}
instead of
data, {}
and set the options included inside {} separated by "," like this:
{
option1: value1,
option2: value2
}
so I have changed this part of your code:
$('#user-email-address').select2('data', {
id: 'test#test.com',
label: 'test#test.com'
});
to:
$('#user-email-address').select2({'data': {
id: 'test#test.com',
label: 'test#test.com'
}
});
and the label is updating now.
updated fiddle
hope it helps.
Edit:
I correct myself, it seems like you can pass the data the way you were doing data,{}
the problem is with the data template..
reading the docs again it seems that the data template should be {id, text} while your ajax result is {id, email}, the set manual section does not work since it tries to return the email from an object of {id, text} with no email. so you either need to change your format selection function to return the text as well instead of email only or remap the ajax result.
I prefer remapping the ajax results and go the standard way since this will make your placeholder work as well which is not working at the moment because the placeholder template is {id,text} also it seems.
so I have changed this part of your code:
processResults: function(data, params) {
var payload = {
results: $.map(data, function(item) {
return { id: item.email, text: item.email };
})
};
return payload;
}
and removed these since they are not needed anymore:
templateResult: function(result) {
return result.email;
},
templateSelection: function(selection) {
return selection.email;
}
updated fiddle: updated fiddle
For me, without AJAX worked like this:
var select = $('.user-email-address');
var option = $('<option></option>').
attr('selected', true).
text(event.target.value).
val(event.target.id);
/* insert the option (which is already 'selected'!) into the select */
option.appendTo(select);
/* Let select2 do whatever it likes with this */
select.trigger('change');
Kevin-Brown on GitHub replied and said:
The issue is that your templating methods are not falling back to text if email is not specified. The data objects being passed in should have the text of the <option> tag in the text property.
It turns out the result parameter to these two methods have more data in them than just the AJAX response!
templateResult: function(result) {
console.log('templateResult', result);
return result.email || result.text;
},
templateSelection: function(selection) {
console.log('templateSelection', selection);
return selection.email || selection.id;
},
Here's the fully functional updated fiddle.

run script when xpages saving document

The xpages contain SAVE button. The xpages also contain InternetAddres field.
When user click SAVE button, need to check first on names.nsf
- Save success if InternetAddress value NOT found in names.nsf view "($Users)"
- Save fail if InternetAddress value found in names.nsf view "($Users)"
How to write the script to do that?
This is the LotusScript version of script:
Set namesview = namesdb.GetView( "($Users)" )
Set namesdoc = namesview.GetDocumentByKey( Lcase(doc.CurrentInternetAddress( 0 ) ), True )
If ( namesdoc Is Nothing ) Then '-- Create New Doc
How to move on xpages?
The latest release of the OpenNTF Domino API adds a checkUnique() method to the View class. It takes two parameters, the first being a key to check against the view (e.g. a String or List of Strings), the second being the current document. After all, if you're checking for a pre-existing document, you don't want to fail just because it finds this document in the view.
So assuming CurrentInternetAddress is a single value field, the code would be:
function continueWithValidUser(namesDB, doc) {
var success = false;
try {
var view = namesDB.getView("($Users)");
success = view.checkUnique(doc.getItemValue("CurrentInternetAddress"),doc);
} catch (e) {
print(e.message);
}
return success;
}
OpenNTF Domino API recycles all handles to Domino objects, so the recycle() calls aren't needed.
In your datasource is a querySave event. You write JS there. It is almost the same code. Just with { } and ;
Remarks:
your app will break when there is more than one address book, so you you would want to use #NameLookup which is quite fast and checks all addressbooks.
unless you need the document getEntry is faster than getDocument
In SSJS your function would look like this:
function continueWithValidUser(namesDB, addressCandidate) {
var success = false;
try {
var view = namesDB.getView("($Users)");
var doc = view.getDocumentByKey(addressCandidate);
success = (doc != null);
doc.recycle();
view.recycle();
} catch (e) {
print(e.message);
}
return success;
}
That should do the trick

use dojo tooltipDialog for every link in the page using parameters

anyone know how to open a tooltipDialog from extlib using parameters.
in csjs I find all links in a webapage and bind them to mouseover. using a key in the link I know which link is clicked, I want to send this key to the toolTipDialog so that I can use that to find the document and display document data in the tooltipDialog.
Currently the only way I have found to open a tooltip dialog is by using XSP.openTooltipDialog("tooltipid",'linkid') which does not seem to allow parameters.
any ideas how to resolve this
Hows this?
require(["dijit/TooltipDialog", "dijit/popup",
"dojo/on", "dojo/dom", "dojo/_base/lang"],
function(ready, TooltipDialog, popup, on, dom, lang){
var myTooltipDialog = new TooltipDialog({
id: 'myTooltipDialog',
style: "width: 300px;",
contentTemplate: "<p>Key is: {key}</p>",
content: 'empty',
onMouseLeave: function(){
popup.close(myTooltipDialog);
},
onOpen: function(pos) {
this.set("content", lang.replace(this.contentTemplate, this.replaceObject));
}
});
/
query('a.hasSelectorClass').on('mouseover', function(){ //
myTooltipDialog.replaceObject = { //
key : this.innerHTML // (inner text in anchor node)
}
popup.open({
popup: myTooltipDialog,
around: this // anchor
});
});
});
Try it and tell if any errors (untested code) :)

.Ajax with jQuery and MVC2

Im trying to create an ajax (post) event that will populate a table in a div on button click.
I have a list of groups, when you click on a group, I would like the table to "disappear" and the members that belong to that group to "appear".
My problem comes up when using jQuery's .ajax...
When I click on the button, it is looking for a controller that doesnt exist, and a controller that is NOT referenced. I am, however, using AREAS (MVC2), and the area is named Member_Select where the controller is named MemberSelect. When I click on the button, I get a 404 stating it cannot find the controller Member_Select. I have examined the link button and it is set to Member_Select when clicked on, but here's the ajax call:
$.ajax({
type: "POST",
url: '/MemberSelect/GetMembersFromGroup',
success: function(html) { $("#groupResults").html(html); }
});
I havent been able to find any examples/help online.
Any thoughts/suggestions/hints would be greatly appreciated.
Thanks!
Have you tried navigating to /MemberSelect/GetMembersFromGroup to see what you get? - if it's 404'ing it's because the route can't be matched to a controller/ action.
I've not used the new areas functionality, but I'm not sure that the URL you've got is correct...I would have thought it would have been /AREANAME/MemberSelect/GetMembersFromGroup...but I could be wrong..!
When I did this, it worked fine. I didn't use POST and I don't know what AREAS means.
$("#item").autocomplete({
source: function(req, responseFn) {
addMessage("search on: '" + req.term + "'<br/>", true);
$.ajax({
url : ajaxUrlBase1 + "GetMatchedCities/" + req.term,
cache : false,
type : "GET", // http method
success : function(msg){
// ajax call has returned
var result = msg;
var a = [];
if (result !== null){
for(var i=0; i < result.length; i++) {
a.push({label: result[i].prop1, id: result[i].prop2});
}
}
responseFn(a);
}
});
}
});
Use:
area_name/controller_name/action_name
Instead of doing $.ajax I would use jQuery Form Plugin.
and have my form set as:
Html.BeginForm("Index","AdminArea/Admin",FormMethod.Post,
new { id="form-user", name="form-user"})
To use jQuery Form Plugin have a look here:
http://arturito.net/2010/12/02/asp-net-mvc2-jquery-form-post-tutorial/
You cold save your url in a Hidden Form element in (Html.HiddenForm()) and use the #id javascript operator to retrieve it. Just found this out today.

Resources