bootstrap typeahead url/redirect - bootstrap-typeahead

$(function(){
var orthoObjs = {};
var orthoNames = [];
var throttledRequest = _.debounce(function(query, process){
$.ajax({
url: 'json/ortho4.json'
,cache: false
,success: function(data){
orthoObjs = {};
orthoNames = [];
_.each( data, function(item, ix, list){
orthoNames.push( item.searchPhr );
orthoObjs[ item.searchPhr ] = item;
});
process( orthoNames );
}
});
}, 300);
$(".typeahead").typeahead({
source: function ( query, process ) {
throttledRequest( query, process );
}
,updater: function (item) {
var url = "orthoObjs[item.searchUrl]";
window.location = url;
Whats the best way to get the redirect to work? I have seen similar questions, but can't get this to work. Documentation on typeahead isn't great. I am using underscore.js for the each function. Just want a simple search query that redirects when the user selects.

I actually got this to work. I got a little help... but here it is. There is the JSON file..
[
{ "id":1, "searchUrl":"invisalign.html", "name":"invisalign" }
,{ "id":2, "searchUrl":"invisalign.html", "name":"invisalign teen" }
,{ "id":3, "searchUrl":"clearbraces.html", "name":"clear braces" }
]
And the HTML code....
Lots of good stuff here.. http://fusiongrokker.com/post/heavily-customizing-a-bootstrap-typeahead
And the search code..
<form method="post" id="myForm" class="navbar-search pull-left">
<input
type="text"
class="search-query typeahead"
placeholder="Search Our Website"
autocomplete="off"
data-provide="typeahead"
/>
<i class="fa-icon-search icon-black"></i>
</form> </li>
$(function(){
var bondObjs = {};
var bondNames = [];
$(".typeahead").typeahead({
source: function ( query, process ) {
//get the data to populate the typeahead (plus an id value)
$.ajax({
url: '/json/bonds.json'
,cache: false
,success: function(data){
bondObjs = {};
bondNames = [];
_.each( data, function(item, ix, list){
bondNames.push( item.name );
bondObjs[ item.name ] = item.searchUrl;
});
process( bondNames );
}
});
}
, updater: function ( selectedName ) {
window.location.href =bondObjs[ selectedName ];
}
});
});
</script>

Related

L.DomUtil.get() modifiers don't update HTML data

Creating a map with markers displayed on it. When clicking a marker, this one has to display a Popup. I extended the L.Popup like this
L.InfrastructurePopup = L.Popup.extend({
options: {
template : "<form id='popup-form'>\
<div>\
<label for='problem'>Problem</label>\
<textarea id='problem' rows='4' cols='46' placeholder='Type your text here'></textarea>\
</div>\
<div>\
<label for='solution'>Solution</label>\
<textarea id='solution' rows='4' cols='46' placeholder='Type your text here'></textarea>\
</div>\
<button id='button-submit' class='btn btn-primary' type='button'>Submit</button>\
</form>",
},
setContent: function () {
this._content = this.options.template;
this.update();
return this;
},
initializeForm(layer, callback)
{
var problem = L.DomUtil.get('problem');
problem.textContent = layer.options.problem ? layer.options.problem : "";
problem.addEventListener('change', (e) =>
{
layer.options.problem = problem.value;
});
var solution = L.DomUtil.get('solution');
solution.textContent = layer.options.solution ? layer.options.solution : "";
solution.addEventListener('change', (e) =>
{
layer.options.solution = solution.value;
});
var buttonSubmit = L.DomUtil.get('button-submit');
buttonSubmit.addEventListener('click', (e) =>
{
callback(layer);
});
}
});
L.infrastructurePopup = function (options, source)
{
return new L.InfrastructurePopup(options, source);
};
I linked it into a custom Marker called InfrastructureMarker that has one and only popup , a InfrastructurePopup. So when it calls the openPopup() function it loads the popup on the map [ map.addLayer(popup) ] and give me the correct datas thanks to method initializeForm() that I call after the addLayer(popup) method.
L.Map.include({
openInfrastructurePopup: function (layer, callback)
{
this.closePopup();
layer._popup._isOpen = true;
this.addLayer(layer._popup);
layer._popup.initializeForm(layer, callback);
}
});
L.InfrastructureMarker = L.Marker.extend({
openPopup: function (callback)
{
if (this._popup && this._map && !this._map.hasLayer(this._popup))
{
this._popup.setLatLng(this._latlng);
this._map.openInfrastructurePopup(this, callback);
}
return this;
},
togglePopup: function (callback)
{
if (this._popup)
{
if (this._popup._isOpen)
{
this._popup._isOpen = false;
this.closePopup();
}
else
{
this.openPopup(callback);
}
}
return this;
},
bindPopup: function (callback, options)
{
var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
anchor = anchor.add(L.Popup.prototype.options.offset);
if (options && options.offset)
{
anchor = anchor.add(options.offset);
}
options = L.extend({offset: anchor}, options);
if (!this._popupHandlersAdded)
{
this
.on('click', () => {this.togglePopup(callback)}, this)
.on('remove', this.closePopup, this)
.on('move', this._movePopup, this);
this._popupHandlersAdded = true;
}
this._popup = new L.infrastructurePopup(options, this).setContent();
return this;
},
});
L.infrastructureMarker = function (latlng, options)
{
return new L.InfrastructureMarker(latlng, options);
};
But if I decide to click on one marker, then on another one without closing the first one, it loads the template, but initializeForm(callback) doesn't change the datas. I checked all the datas to know if it was empty or something but everything worked, I absolutely don't know where the problem is. I suppose the popup is not yet set on the DOM before my L.DomUtils.get fire but I shouldn't see undefined elements in console.log when I'm getting them.
I actually found what was happening :
Actually, when the L.map calls its closePopup function , it destroys the layer.
So after that, it creates a new one to display. BUT the remaining HTML from the previous kind of still exists.
So I finally bound exact same Ids to two HTML tags. Heresy !
My solution became what's next :
L.InfrastructurePopup = L.Popup.extend({
setContent: function (layer)
{
var template = "<form id='popup-form'>\
<div>\
<label for='problem'>Problème Identifié</label>\
<textarea id='" + layer._leaflet_id + "-problem' rows='4' cols='46' placeholder='Type your text here'></textarea>\
</div>\
<div>\
<label for='solution'>Solution Proposée</label>\
<textarea id='" + layer._leaflet_id + "-solution' rows='4' cols='46' placeholder='Type your text here'></textarea>\
</div>\
<button id='" + layer._leaflet_id + "-button-submit' class='btn btn-primary' type='button'>Submit</button>\
</form>";
this._content = template;
this.update();
return this;
},
initializeForm: function(layer, callback)
{
console.log(L.DomUtil.get(layer._leaflet_id+'-problem'));
var problem = L.DomUtil.get(layer._leaflet_id + '-problem');
problem.textContent = layer.options.problem ? layer.options.problem : "";
problem.addEventListener('change', (e) =>
{
layer.options.problem = problem.value;
});
var solution = L.DomUtil.get(layer._leaflet_id + '-solution');
solution.textContent = layer.options.solution ? layer.options.solution : "";
solution.addEventListener('change', (e) =>
{
layer.options.solution = solution.value;
});
var buttonSubmit = L.DomUtil.get(layer._leaflet_id + '-button-submit');
buttonSubmit.addEventListener('click', (e) =>
{
callback(layer);
});
}
});
L.infrastructurePopup = function (options, source)
{
return new L.InfrastructurePopup(options, source);
};
Calling setContent when creating my InfrastructurePopup with the layer_id and set it into my template made it work.
I got : '97-problem' or '99-problem' and '97-solution' or '99-solution

populate select with datajson using React js

I'm trying to populate a select using React js, I'm using the example given on the react js docs(https://facebook.github.io/react/tips/initial-ajax.html) , which uses jquery to manage the ajax calling, I'm not able to make it work, so far i have this:
here the codepen : http://codepen.io/parlop/pen/jrXOWB
//json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc ase_id":"CTSTESTING","name":"CTS-Testing"}]
//using jquery to make a ajax call
var App = React.createClass({
getInitialState: function() {
return {
opts:[]
};
},
componentDidMount: function() {
var source="https://api.myjson.com/bins/3dbn8";
this.serverRequest = $.get(source, function (result) {
var arrTen = result[''];
for (var k = 0; k < ten.length; k++) {
arrTen.push(<option key={opts[k]} value={ten[k].companycase_id}> {ten[k].name} </option>);
}
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
<select id='select1'>
{this.state.opts}
</select>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('root')
);
html
<div id="root"></div>
any idea how to make it works, thanks.
You need to call setState to actually update your view. Here's a workable version.
//json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc ase_id":"CTSTESTING","name":"CTS-Testing"}]
//using jquery to make a ajax call
var App = React.createClass({
getInitialState: function() {
return {
opts:[]
};
},
componentDidMount: function() {
var source="https://api.myjson.com/bins/3dbn8";
this.serverRequest = $.get(source, function (result) {
var arrTen = [];
for (var k = 0; k < result.length; k++) {
arrTen.push(<option key={result[k].companycase_id} value={result[k].companycase_id}> {result[k].name} </option>);
}
this.setState({
opts: arrTen
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
<select id='select1'>
{this.state.opts}
</select>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('root')
);

Update vuejs model value using jquery-chosen plugin

Trying to use jquery-chosen with vue, the problem is that this plugin hides the actual select that I applied v-model, so when I select a value vue doesn't recognize it as a select change event and model value is not updated.
The value of the select is being changed actually when I select something, I've inspected this with console.log to see the selected value.
http://jsfiddle.net/qfy6s9Lj/3/
I could do vm.$data.city = $('.cs-select').val(), that seems to work,
But is there another option? If the value of the select was changed why vue doesn't see this?
#swift's answer got pretty close, but as #bertrand pointed out, it doesn't work for multiselects. I've worked something out that works with both cases: http://jsfiddle.net/seanwash/sz8s99xx/
I would have just commented but I don't have enough rep to do so.
Vue.directive('chosen', {
twoWay: true, // note the two-way binding
bind: function () {
$(this.el)
.chosen({
inherit_select_classes: true,
width: '30%',
disable_search_threshold: 999
})
.change(function(ev) {
// two-way set
// Construct array of selected options
var i, len, option, ref;
var values = [];
ref = this.el.selectedOptions;
for (i = 0, len = ref.length; i < len; i++) {
option = ref[i];
values.push(option.value)
}
this.set(values);
}.bind(this));
},
update: function(nv, ov) {
// note that we have to notify chosen about update
$(this.el).trigger("chosen:updated");
}
});
var vm = new Vue({
data: {
city: 'Toronto',
cities: [{text: 'Toronto', value: 'Toronto'},
{text: 'Orleans', value: 'Orleans'}]
}
}).$mount("#search-results");
I am opened for other suggestions, but for the time-being I did it this way:
html
<div id='search-results'>
{{city}}
<select class="cs-select" v-model='city'>
<option value="Toronto">Toronto</option>
<option value="Orleans">Orleans</option>
</select>
</div>
js
window.vm = new Vue({
el: '#search-results',
data: {
city: 'Toronto',
}
})
$('.cs-select').chosen({
inherit_select_classes: true,
width: '30%'
}).change( function() {
vm.$data.city = $('.cs-select').val()
})
Update: Be advised this doesn't work from within a v-for loop. A related question that deals with that is available here.
Going off of #kaktuspalme's solution, and with help from my friend Joe Fleming, I came up with a solution that works with Vue 2 and allows single and multiple selections:
Vue.directive('chosen', {
inserted: function(el, binding, vnode) {
jQuery(el).chosen().change(function(event, change) {
if (Array.isArray(binding.value)) {
var selected = binding.value;
if (change.hasOwnProperty('selected')) {
selected.push(change.selected);
} else {
selected.splice(selected.indexOf(change.deselected), 1);
}
} else {
var keys = binding.expression.split('.');
var pointer = vnode.context;
while (keys.length > 1)
pointer = pointer[keys.shift()];
pointer[keys[0]] = change.selected;
}
});
},
componentUpdated: function(el, binding) {
jQuery(el).trigger("chosen:updated");
}
});
Use it like this:
<select v-model="mymodel" v-chosen="mymodel">...</select>
It works with multiple="multiple" and even with nested state, e.g.:
<select v-model="nested.mymodel" v-chosen="nested.mymodel">...</select>
See the fiddle here: https://jsfiddle.net/tylercollier/bvvvgyp0/5/
Answer:
http://jsfiddle.net/qfy6s9Lj/5/
<div id='search-results'>
Vue model value <br>
{{city}}
<hr>
Select value:
<select class="cs-select" v-chosen>
<option value="Toronto">Toronto</option>
<option value="Orleans">Orleans</option>
</select>
</div>
Vue.directive('chosen', {
bind: function () {
var vm = this.vm;
this.el.options = vm.cities;
this.el.value = vm.city;
$(this.el).chosen({
inherit_select_classes: true,
width: '30%',
disable_search_threshold: 999})
.change( function() {
vm.city = this.el.value;
}.bind(this)
);
}
});
var vm = new Vue({
data: {
city: 'Toronto',
cities: ['Toronto', 'Orleans']
}
}).$mount("#search-results");
UPDATE: an even better solution (thanks to simplesmiler):
http://jsfiddle.net/simplesmiler/qfy6s9Lj/8/
I made an update for vue2.
Vue.directive('chosen', {
selected: null,
inserted: function (el, binding) {
selected = binding.value;
$(el).chosen().change(function(event, change) {
if(change.hasOwnProperty('selected')) {
selected.push(change.selected);
} else {
selected.splice(selected.indexOf(change.deselected), 1);
}
});
},
componentUpdated: function(el, binding) {
selected = binding.value;
$(el).trigger("chosen:updated");
}
});
var vm = new Vue({
el: '#app',
data: {
selected: [],
cities: [{id: 1, value: "Toronto"}, {id: 2, value: "Orleans"}, {id: 3, value: "Bern"}]
}
});
See: https://jsfiddle.net/kaktuspalme/zenksm2b/
Code taken from #kaktuspalme answer. It works with non-multiple elements now and only for non-multiple.
Vue.directive('chosensingle', {
inserted: function (el, binding) {
var selected = binding.value;
$(el).chosen().change(function(event, change) {
if(change.hasOwnProperty('selected')) {
selected.value = change.selected;
} else {
selected.value ='';
}
});
},
componentUpdated: function(el, binding) {
$(el).trigger("chosen:updated");
}
});
Comments from #Tyler Collier are taken into account
But be carefully,property you use in v-model should be defined as array , e.g. applicantId: [] otherwise it doesn't work

Pass polymer form data to rest api

I'm looking for some way to pass data from a Polymer form fields to REST API,
actually, I'm using core-ajax to do it but I think is a bit heavy method to do it.
Are any standard way to do it?
This is my code:
<template>
<section>
<file-input class="blue" id="file" extensions='[ "xls" ]' maxFiles="1">{{ FileInputLabel }}</file-input>
</section>
<section>
<paper-button raised class="blue" disabled?="{{ (! Validated) || (Submitted) }}" on-tap="{{ Submit }}">
<core-icon icon="send"></core-icon>
Process
</paper-button>
</section>
<paper-toast id="toast" text=""></paper-toast>
<core-ajax id="ajax" url="/import-pdi" method="POST" handleAs="json" response="{{ response }}" on-core-complete="{{ SubmitFinished }}"></core-ajax>
</template>
<script>
Polymer("import-pdi-form", {
Validated: false,
Submitted: false,
FileInputLabel: "SELECT",
ready: function () {
this.shadowRoot.querySelector("#file").addEventListener("change", function(event) {
var container = document.querySelector("import-pdi-form");
container.Validated = (event.detail.valid.length != 0);
if (event.detail.valid.length == 0) {
container.shadowRoot.querySelector("#toast").text = "Invalid Format";
container.shadowRoot.querySelector("#toast").show();
container.FileInputLabel = "SELECCIONA L'ARXIU";
}
else {
container.FileInputLabel = event.detail.valid[0].name;
var form_data = new FormData();
form_data.append("file", event.detail.valid[0], event.detail.valid[0].name);
container.shadowRoot.querySelector("#ajax").body = form_data;
container.shadowRoot.querySelector("#ajax").contentType = null;
}
});
},
Submit: function() {
if ((this.Validated) && (! this.Submitted)) {
this.Submitted = true;
this.shadowRoot.querySelector("#ajax").go();
}
},
SubmitFinished: function(event, detail, sender) {
if (detail.xhr.status == 200) {
this.shadowRoot.querySelector("#toast").text = JSON.parse(detail.xhr.response).message;
}
else {
this.shadowRoot.querySelector("#toast").text = "Server Error";
}
this.shadowRoot.querySelector("#toast").show();
this.FileInputLabel = "SELECCIONA L'ARXIU";
this.shadowRoot.querySelector("#file").reset();
this.Submitted = false;
}
});
</script>
For submitting a form that contains custom elements we currently recommend that you use the ajax-form element. It looks like you may already be using the file-input element by the same author, so the two should work well together.

alert() message isn't being called in my form

Firebug is giving me no error messages, but it's not working. The idea is regardless of whether the user picks an option from dropdown or if they type in something in search box, I want the alert() message defined below to alert what the value of the variable result is (e.g. {filter: Germany}). And it doesn't. I think the javascript breaks down right when a new Form instance is instantiated because I tried putting an alert in the Form variable and it was never triggered. Note that everything that pertains to this issue occurs when form.calculation() is called.
markup:
<fieldset>
<select name="filter" alter-data="dropFilter">
<option>Germany</option>
<option>Ukraine</option>
<option>Estonia</option>
</select>
<input type="text" alter-data="searchFilter" />
</fieldset>
javascript (below the body tag)
<script>
(function($){
var listview = $('#listview');
var lists = (function(){
var criteria = {
dropFilter: {
insert: function(value){
if(value)
return handleFilter("filter", value);
},
msg: "Filtering..."
},
searchFilter: {
insert: function(value){
if(value)
return handleFilter("search", value);
},
msg: "Searching..."
}
}
var handleFilter = function(key,value){
return {key: value};
}
return {
create: function(component){
var component = component.href.substring(component.href.lastIndexOf('#') + 1);
return component;
},
setDefaults: function(component){
var parameter = {};
switch(component){
case "sites":
parameter = {
'order': 'site_num',
'per_page': '20',
'url': 'sites'
}
}
return parameter;
},
getCriteria: function(criterion){
return criteria[criterion];
},
addCriteria: function(criterion, method){
criteria[criterion] = method;
}
}
})();
var Form = function(form){
var fields = [];
$(form[0].elements).each(function(){
var field = $(this);
if(typeof field.attr('alter-data') !== 'undefined') fields.push(new Field(field));
})
}
Form.prototype = {
initiate: function(){
for(field in this.fields){
this.fields[field].calculate();
}
},
isCalculable: function(){
for(field in this.fields){
if(!this.fields[field].alterData){
return false;
}
}
return true;
}
}
var Field = function(field){
this.field = field;
this.alterData = false;
this.attach("change");
this.attach("keyup");
}
Field.prototype = {
attach: function(event){
var obj = this;
if(event == "change"){
obj.field.bind("change", function(){
return obj.calculate();
})
}
if(event == "keyup"){
obj.field.bind("keyup", function(e){
return obj.calculate();
})
}
},
calculate: function(){
var obj = this,
field = obj.field,
msgClass = "msgClass",
msgList = $(document.createElement("ul")).addClass("msgClass"),
types = field.attr("alter-data").split(" "),
container = field.parent(),
messages = [];
field.next(".msgClass").remove();
for(var type in types){
var criterion = lists.getCriteria(types[type]);
if(field.val()){
var result = criterion.insert(field.val());
container.addClass("waitingMsg");
messages.push(criterion.msg);
obj.alterData = true;
alert(result);
initializeTable(result);
}
else {
return false;
obj.alterData = false;
}
}
if(messages.length){
for(msg in messages){
msgList.append("<li>" + messages[msg] + "</li");
}
}
else{
msgList.remove();
}
}
}
$('#dashboard a').click(function(){
var currentComponent = lists.create(this);
var custom = lists.setDefaults(currentComponent);
initializeTable(custom);
});
var initializeTable = function(custom){
var defaults = {};
var custom = custom || {};
var query_string = $.extend(defaults, custom);
var params = [];
$.each(query_string, function(key,value){
params += key + ': ' + value;
})
var url = custom['url'];
$.ajax({
type: 'GET',
url: '/' + url,
data: params,
dataType: 'html',
error: function(){},
beforeSend: function(){},
complete: function() {},
success: function(response) {
listview.html(response);
}
})
}
$.extend($.fn, {
calculation: function(){
var formReady = new Form($(this));
if(formReady.isCalculable) {
formReady.initiate();
}
}
})
var form = $('fieldset');
form.calculation();
})(jQuery)
Thank you for anyone who responds. I spent a lot of time trying to make this work.
The initial problem as to why the alert() was not being triggered when Form is instantiated is because, as you can see, the elements property belongs to the Form object, not fieldset object. And as you can see in the html, I place the fields as descendents of the fieldset object, not form.