This is the code:
var MyModel = Backbone.Model.extend({
defaults: {std:"",
pod:""
}
});
var MyView = Backbone.View.extend({
tagName:'ul',
events: {
'change input' : 'changed', // When input changes, call changed.
'hover .std' : 'timepick', //
'mouseout .std': 'doesntwork'
},
template:_.template($('#mytemplate').html()),
initialize: function() {
this.model.bind('change:pod',this.render,this); // When pod changes, re-render
},
timepick: function(e) {
$('.std').each(function(){
$.datepicker.setDefaults({dateFormat:'mm-dd'});
$(this).datetimepicker({timeFormat:'hh:mm',ampm:false});
});
},
doesntwork: function() {
// Would this.model.set here but mouseout happens when you select date/time values with mouse
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
changed: function(e) {
var value = $(e.currentTarget).val(); // Get Change value
var cls = $(e.currentTarget).attr('class'); //Get Class of changed input
var obj = {};
obj[cls] = value; // The model variables match class names
this.model.set(obj); // this.model.set({'std':value})
}
});
I have a datetimepicker in the UI I'm working on, and having difficulties assigning the value that is selected from the datetimepicker to MyModel.
It appears from using console.log output that 'change input' is triggered when clicking on the DTP and assigns the default value of (MM-DD 00:00). Even when you select a different date/time value than the default, the 'change input' is not triggered again, unless you click on the input box (for a second time), and then the correct value is assigned. Not very user-friendly.
So I had the idea that I would just assign the value on mouseout, which didn't work since mouseout happens when you start to select date/time values. I also tried blur, and that didn't work either.
Where am I going wrong?
Edit: Here is a jsfiddle.net link that illustrates my problem http://jsfiddle.net/9gSUe/1/
Looks like you're getting tripped up by jQuery UI's CSS. When you bind a datepicker to an <input>, jQuery UI will add a hasDatepicker class to the <input>. Then you do this:
var cls = $(e.currentTarget).attr('class');
on the <input> and get 'std hasDatepicker' in cls.
There are too many things that will mess around with class so you're better off using something else to identify the property you want to change. You could use an id if there is only one std:
<!-- HTML -->
<input id="std" class="std" ...>
// JavaScript
var cls = e.currentTarget.id;
or the name attribute:
<!-- HTML -->
<input name="std" class="std" ...>
// JavaScript
var cls = $(e.currentTarget).attr('name');
or perhaps even a HTML5 data attribute:
<!-- HTML -->
<input class="std" data-attr="std" ...>
// JavaScript
var cls = $(e.currentTarget).data('attr');
I think the name attribute would be the most natural: http://jsfiddle.net/ambiguous/RRKVJ/
And a couple side issues:
Your fiddle was including multiple versions of jQuery and that's generally a bad idea.
You don't have to build an object for set, you can say just m.set(attr, value) if you're just setting one attribute.
You don't have to $(this.el) in your views, newer Backbones have this.$el already cached.
console.log can handle multiple arguments so you can say console.log('Std: ', attrs.std, ' Pod: ', attrs.pod, ' Poa: ', attrs.poa); instead of console.log('Std: ' + attrs.std + ' Pod: ' + attrs.pod + ' Poa: ' + attrs.poa); if you don't want + stringify things behind your back.
Related
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')
I am using vue-i18n and I need to translate a sentence with an anchor tag in the middle. Obviously I want to keep the html specific markup out of my translations, but how best to handle this?
Consider the following example:
This is a test sentence which cannot
be split
or it will not make sense
The only solution I can come up with is:
{
"en": {
"example": "This is a test sentence which cannot {linkOpen}be split{linkClose} or it will not make sense"
}
}
and then in the component template
<p v-html="$t('example', {
'linkOpen': `<a href="https://example/com" class="test-class test-another-class">`,
'linkClose: '</a>'
})
"></p>
Not exactly elegant however...
Edit: I've tested this and it doesn't actually work (can't put html in params) so now I'm really out of ideas!
You can come up with some simple markup for links and write a small transformation function, for example:
//In this example links are structured as follows [[url | text]]
var text = `This is a test sentence which
cannot [[https://example.com | be split]] or it will not make sense`
var linkExpr = /\[\[(.*?)\]\]/gi;
var linkValueExpr = /(\s+\|\s+)/;
var transformLinks = (string) => {
return text.replace(linkExpr, (expr, value) => {
var parts = value.split(linkValueExpr);
var link = `${parts[2]}`;
return link;
});
}
alert(transformLinks(text));
JSFiddle: https://jsfiddle.net/ru5smdy3/
With vue-i18n it will look like this (which of course you can simplify):
<p v-html="transformLinks($t('example'))"></p>
You can put the HTML into an element that is not part of the displayed DOM and then extract its textContent. This may not work for what you're actually trying to do, though. I can't tell.
new Vue({
el: '#app',
data: {
html: `This is a test sentence which cannot
be split
or it will not make sense`,
utilityEl: document.createElement('div')
},
methods: {
htmlToText: function (html) {
this.utilityEl.innerHTML = html;
return this.utilityEl.textContent;
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>
<div id="app">
<p v-html="html"></p>
<p>{{htmlToText(html)}}</p>
</div>
I have found myself in a similar situation, and I propose using Vue-i18n slots.
I have a JSON i18n file which had error messages that were html. These rendered fine but they will not be compiled as vue templates, and cannot have bindings. I want to call an onclick function when users click the link in a given error message.
In my example I have a cake-state json with some status messages:
// cake_state.json, where I want links in error messages to call a function when clicked
{
"state":{
"stage": {
"mixing": "Cake is being mixed. The current time is {time}",
"resting": "Cake is resting. The current time is {time}",
"oven": "Cake is cooking. The current time is {time}"
},
"error": {
"ovenIssue": "Oven of brand is malfunctioning. Click {email_support_link} to get help",
"chefIssue": "Chef is down. Click {email_support_link} to get help",
"leakIssue": "There is a leak"
},
}
}
Now if we have some Vue SFC, with the template as such:
<template>
<div>
<i18n :path="getMessage">
<!-- enter various i18n slots -->
<template #time>
<span>{{ getTime }}</span>
</template>
<template #email_support_link>
<!-- binding now works because it is not v-html -->
<a href="" #click.prevent="getRightSupportDepartment">here</span>
</template>
</i18n>
</div>
</template>
...
// js
computed: {
getTime(): string { //implementation ...},
getRightSupportDepartment(): string { //implementation ...},
//return strings that are keys to cake_state.json messages
getMessage(): string {
...
switch (this.cakeState) {
case Failure.Overheat:
return "state.error.ovenIssue";
case Failure.ChefIdle:
return "state.error.chefIssue";
case Failure.LeakSensor:
return "state.error.leakIssue";
So what we see here is:
the getMessage function provides us the key to the message in the i18n JSON. This is passed into i18n component
the <template #XXX> slots in the i18n component's scope are supplied with this key from the function, which gets the corresponding message, and then
if the relevant message has any of the keywords, it gets put in from the corresponding template.
To re-iterate, it helps to provide a means to have vue bindings to html elements which would otherwise be served from the i18n json as raw html.
For example now we might see "Oven of brand is malfunctioning. Click here to get help", and we can run an onclick function when user clicks 'here'.
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.
I would like to use an autocomplete with ajax. So my goal is to have:
When the user types something in the text field, some suggestions provided by the server appear (I have to find suggestions in a database)
When the user presses "enter", clicks somewhere else than in the autocomplete box, or when he/she selects a suggestion, the string in the textfield is sent to the server.
I first tried to use the autocomplete widget provided by lift but I faced three problems:
it is meant to be an extended select, that is to say you can originally only submit suggested values.
it is not meant to be used with ajax.
it gets buggy when combined with WiringUI.
So, my question is: How can I combine jquery autocomplete and interact with the server in lift. I think I should use some callbacks but I don't master them.
Thanks in advance.
UPDATE Here is a first implementation I tried but the callback doesn't work:
private def update_source(current: String, limit: Int) = {
val results = if (current.length == 0) Nil else /* generate list of results */
new JsCmd{def toJsCmd = if(results.nonEmpty) results.mkString("[\"", "\", \"", "\"]") else "[]" }
}
def render = {
val id = "my-autocomplete"
val cb = SHtml.ajaxCall(JsRaw("request"), update_source(_, 4))
val script = Script(new JsCmd{
def toJsCmd = "$(function() {"+
"$(\"#"+id+"\").autocomplete({ "+
"autocomplete: on, "+
"source: function(request, response) {"+
"response("+cb._2.toJsCmd + ");" +
"}"+
"})});"
})
<head><script charset="utf-8"> {script} </script></head> ++
<span id={id}> {SHtml.ajaxText(init, s=>{ /*set cell to value s*/; Noop}) } </span>
}
So my idea was:
to get the selected result via an SHtml.ajaxText field which would be wraped into an autocomplete field
to update the autocomplete suggestions using a javascript function
Here's what you need to do.
1) Make sure you are using Lift 2.5-SNAPSHOT (this is doable in earlier versions, but it's more difficult)
2) In the snippet you use to render the page, use SHtml.ajaxCall (in particular, you probably want this version: https://github.com/lift/framework/blob/master/web/webkit/src/main/scala/net/liftweb/http/SHtml.scala#L170) which will allow you to register a server side function that accepts your search term and return a JSON response containing the completions. You will also register some action to occur on the JSON response with the JsContext.
3) The ajaxCall above will return a JsExp object which will result in the ajax request when it's invoked. Embed it within a javascript function on the page using your snippet.
4) Wire them up with some client side JS.
Update - Some code to help you out. It can definitely be done more succinctly with Lift 2.5, but due to some inconsistencies in 2.4 I ended up rolling my own ajaxCall like function. S.fmapFunc registers the function on the server side and the function body makes a Lift ajax call from the client, then invokes the res function (which comes from jQuery autocomplete) on the JSON response.
My jQuery plugin to "activate" the text input
(function($) {
$.fn.initAssignment = function() {
return this.autocomplete({
autoFocus: true,
source: function(req, res) {
search(req.term, res);
},
select: function(event, ui) {
assign(ui.item.value, function(data){
eval(data);
});
event.preventDefault();
$(this).val("");
},
focus: function(event, ui) {
event.preventDefault();
}
});
}
})(jQuery);
My Scala code that results in the javascript search function:
def autoCompleteJs = JsRaw("""
function search(term, res) {
""" +
(S.fmapFunc(S.contextFuncBuilder(SFuncHolder({ terms: String =>
val _candidates =
if(terms != null && terms.trim() != "")
assigneeCandidates(terms)
else
Nil
JsonResponse(JArray(_candidates map { c => c.toJson }))
})))
({ name =>
"liftAjax.lift_ajaxHandler('" + name
})) +
"=' + encodeURIComponent(term), " +
"function(data){ res(data); }" +
", null, 'json');" +
"""
}
""")
Update 2 - To add the function above to your page, use a CssSelector transform similar to the one below. The >* means append to anything that already exists within the matched script element. I've got other functions I've defined on that page, and this adds the search function to them.
"script >*" #> autoCompleteJs
You can view source to verify that it exists on the page and can be called just like any other JS function.
With the help of Dave Whittaker, here is the solution I came with.
I had to change some behaviors to get:
the desired text (from autocomplete or not) in an ajaxText element
the possibility to have multiple autocomplete forms on same page
submit answer on ajaxText before blurring when something is selected in autocomplete suggestions.
Scala part
private def getSugggestions(current: String, limit: Int):List[String] = {
/* returns list of suggestions */
}
private def autoCompleteJs = AnonFunc("term, res",JsRaw(
(S.fmapFunc(S.contextFuncBuilder(SFuncHolder({ terms: String =>
val _candidates =
if(terms != null && terms.trim() != "")
getSugggestions(terms, 5)
else
Nil
JsonResponse(JArray(_candidates map { c => JString(c)/*.toJson*/ }))
})))
({ name =>
"liftAjax.lift_ajaxHandler('" + name
})) +
"=' + encodeURIComponent(term), " +
"function(data){ res(data); }" +
", null, 'json');"))
def xml = {
val id = "myId" //possibility to have multiple autocomplete fields on same page
Script(OnLoad(JsRaw("jQuery('#"+id+"').createAutocompleteField("+autoCompleteJs.toJsCmd+")"))) ++
SHtml.ajaxText(cell.get, s=>{ cell.set(s); SearchMenu.recomputeResults; Noop}, "id" -> id)
}
Script to insert into page header:
(function($) {
$.fn.createAutocompleteField = function(search) {
return this.autocomplete({
autoFocus: true,
source: function(req, res) {
search(req.term, res);
},
select: function(event, ui) {
$(this).val(ui.item.value);
$(this).blur();
},
focus: function(event, ui) {
event.preventDefault();
}
});
}
})(jQuery);
Note: I accepted Dave's answer, mine is just to provide a complete answer for my purpose
I am having trouble using JQueryUI with salesforce standard elements. Basically, I want to auto suggest the record names to the user, instead of the user clicking on the salesforce search button.
<apex:inputField value="{!MyRecord.ChildRecord__c}" id="inpId" required="true/>
<script>
jq$(document.getElementById('{!$Component.inpId}')).autocomplete( {
minLength: 2,
autoFocus: true,
source: mySource
});
</script>
Therefore, I want to know if anyone attempted to use JQueryUI with standard salesforce input elements. In my case, the JQueryUI events are not firing for salesforce elements.
{!$Component.[elementid]} doesn't always work for me; I'm not sure why. I prefer to use the Attribute Ends With Selector (http://api.jquery.com/attribute-ends-with-selector/).
Try something like this:
<apex:includeScript value="/soap/ajax/18.0/connection.js" />
<apex:includeScript value="/soap/ajax/18.0/apex.js" />
<script>
var j$ = jQuery.noConflict();
j$(document).ready(function(){init();});
function init()
{
var mySourceText = "ActionScript AppleScript Asp BASIC C "
+ "C++ Clojure COBOL ColdFusion Erlang Fortran Groovy "
+ "Haskell Java JavaScript Lisp Perl PHP Python Ruby "
+ "Scala Scheme";
var mySource = mySourceText.split(" ");
j$("[id$='myInput']").autocomplete({
minLength: 2,
autoFocus: true,
source: function(request, response){
response(GetSourceAjaxAPI(request.term)); }
});
}
function GetSourceAjaxAPI(s)
{
var result = sforce.apex.execute("TestAutocomplete",
"GetAutocompleteValuesAjaxAPI", {SearchTerm:s});
return result;
}
</script>
<apex:form >
<apex:pageblock >
<apex:pageblocksection >
<apex:pageblocksectionitem >
<apex:inputfield id="myInput" value="{!Contact.FirstName}" />
</apex:pageblocksectionitem>
</apex:pageblocksection>
</apex:pageblock>
</apex:form>
Controller:
global class TestAutocomplete
{
global TestAutocomplete(ApexPages.StandardController myStandardController) {}
webservice static List<String>
GetAutocompleteValuesAjaxAPI(String SearchTerm)
{
String mySourceText = 'ActionScript AppleScript Asp BASIC C '
+ 'C++ Clojure COBOL ColdFusion Erlang Fortran Groovy '
+ 'Haskell Java JavaScript Lisp Perl PHP Python Ruby '
+ 'Scala Scheme';
List<String> mySourceList = mySourceText.split(' ');
List<String> myReturnList = new List<String>();
for(String s : mySourceList)
{
if(s.contains(SearchTerm)){ myReturnList.add(s); }
}
return myReturnList;
}
}
Hope that helps,
Matt
I figured out the reason why JQeuryUI was not working on SalesForce standard input element. I was trying to use JQueryUI autocomplete on the input element. The action function that was supposed to be invoked was not called because I did not have
<apex:actionFunction immediate="true" />
That is we must have immediate=true attribute set so that action function is called immediately. If we do not have this attribute set, SalesForce tries to validate all the standard input elements and if the validation fails, action function is never called.