Utilizing Bootstrap's typeahead as a search function - search

I've got typeahead working just fine, but I am too inexperienced with the Javascript to understand how to turn the typed results into a link.
<input type="text"
class="span3"
data-provide="typeahead"
placeholder="City Search:"
data-items="6"
autocomplete="off"
data-source=["Neuchatel","Moutier"]">
So, I really just want to know how to turn the strings from data-source into links to other pages. Hopefully this is fairly simple.
thanks!

You can turn the strings into links easily..
<input type="text" data-provide="typeahead" data-source="["/foo.html","http://www.google.com","/about.html"]">
Are you also looking to take the link from the input and then navigate to the selected page?
EDIT: Navigate to item selected in typeahead..
In this case you'd define an object map that contain keys (label) and values (url) like..
var data = {
"login":"/login",
"home":"/",
"user":"/user",
"tags":"/tags",
"google":"http://google.com"
};
Then you'd initiate the typeahead. The source and updater functions would be defined to handle 1) creating the typeahead data source array from the map object, and 2) navigate to the appropriate url when an item is selected..
$('.typeahead').typeahead({
minLength:2,
updater: function (item) {
/* navigate to the selected item */
window.location.href = data[item];
},
source: function (typeahead, query) {
var links=[];
for (var name in data){
links.push(name);
}
return links;
}
});
Demo on Bootply

Related

How insert result of a Netlify function into the HTML web page whose form called the function (example: calculator)

Background:
I'm coming from the server-side world of Rails, and trying to figure out the Netlify static html + serverless functions approach to doing a few extremely basic landing page web apps which need a serverless function to insert data into an HTML page.
I'm trying to start with the simplest possible case of an HTML page with a form and a serverless function that returns a result back to the page. (e.g., no static site generators).
I have not found any Netlify tutorials that show how a HTML page can have a form that posts to a function which then returns the result of that function back into the same web page.
The simplest sample app I can think of is a page asks a question, the user POSTs their answer to a serverless function, and the same HTML page is updated with the result of the function... a trivial case being to display "your answer was X" above the form. (It is immaterial to me whether the actual page is rewritten again with the result string included, or the result string is dynamically inserted by somehow poking the string to the div, so long as the result string originates in a serverless function; integrating serverless functions results with HTML pages is what I'm trying to learn.)
In the code below a simple HTML page below displays a form, the form POSTs an answer to a javascript function check_answer.js, and the javascript function erases the current page and displays the string "Your answer was XXXX".
That was simple to do, and lots of tutorials show how to have a function accept a form post then return a result string to the browser (overwriting the prior page).
My question:
How can the serverless function insert the result string back into the original HTML page (at the div id="answer") instead of outputting the result to a blank page?
Current code:
# index.html
<html>
<head>
<title>A test form</title>
</head>
<body>
<div id="answer">
</div>
<p>How much is 1 + 3?</p>
<p>form using POST:</p>
<form method="post" name="calc 2" action="/.netlify/functions/check_answer" id="calcform2" data-netlify="true" >
<p>
<label for="my_answer">Answer:</label>
<input type="text" name="my_answer" id="my_answer">
<label for="my_comment">Comment:</label>
<input type="text" name="my_comment" id="my_comment">
</p>
<p>
<input type="submit">
</p>
</form>
</body>
</html>
# functions/check_answer.js
exports.handler = async event => {
console.log(event.queryStringParameters);
console.log(event);
console.log(event.body);
if (event.httpMethod == 'POST')
{
console.log('is POST');
var params = parseQuery(event.body);
console.log(params);
var answer_string = params['my_answer'];
}
else
{
console.log('is GET');
var answer_string = event.queryStringParameters.my_answer || 'empty'
};
return {
statusCode: 200,
body: `Your answer was ${answer_string}`,
}
}
// handle parsing form query aaaa=bbbbb&cccc=dddd into hash object
// from https://stackoverflow.com/a/13419367/597992
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}

split string in nodejs

I am working on node js with mongodb. I am getting the value of doc in view file.
{{#each doc}}
<div class="abstract" data-reactid=".1ejbmifi4u8.1.1.0.1.2.0:$35.0.0.1.2.0" id="content">
{{this.content}}</div>
{{/each}}
this will print the value of content.
I want to print only 40 characters of this content on view page and then want to implement "read more" to go to full content page.
Guessing by the syntax, you are using Handlebars or some similar derivative. If it's not Handlebars, you'll have to modify the below a little to match your framework, but it should be similar. Leave a comment if it's not and I'll edit.
Handlebars supports what is known as helpers which allow you to manipulate data fed into your views.
You could write a helper named, for example, excerpt, like so:
Handlebars.registerHelper('excerpt', function(data, url) {
if (data.length > 40) {
return new Handlebars.SafeString(
data.substring(0, 40) + '… Read more"
);
}
return data;
});
You can then use it like {{excerpt this.content this.readMoreUrl}}, where this.readMoreUrl is whichever property provides the relevant URL.
I am not familiar with the JavaScript MVC but You can do something like this in JS:
content = this.content
if(content.length > 40)
content_to_print = content.substr(0,40)
content_to_print = content_to_print+' Read More...'
Hope this helps!

selectize.js call href to add new option

The documentation of selectize already explains how to use create: function (input, callback) {....} to add a new item to the database.
In my case, the base model of a selectbox not only contains the option name but also other data.
P.e.: I have a selectbox with countries.
The options are filled from a model "Countries" which contains "country_name", "top_level", "currency". The selectbox only shows "country_name".
If a user wants to add a new country, I want to open a bootstrap modal, let the user add the new country data and after saving I want to refresh the selectbox using refreshOptions ().
I tried to change in selectize.js in line 741 from
'option_create': function(data, escape) {
return '<div class="create">Add <strong>' + escape(data.input) + </strong>…</div>';
to
'option_create': function(data, escape) {
return '<a data-toggle="modal" data-keyboard="false" data-backdrop="static" data-target="#modal" href="... some link ...">New country</a>';
I can see the link after writing a not existing country in the seletbox but when I click on it nothing happens.
How can I fix this? I am already to close to give up :-)
++++++++++++++++++++++++++++++++++
Javascript for removing option:
<script type="text/javascript">
$(".chosen-search-94-departID").selectize({
create: true,
sortField: {field: 'text'},
onOptionAdd: function (value, $item) {
var link='... link ...' + value;
load_modal_content (link, '... csrf ...');
$('#modal').modal('show');
$item.selectize.removeOption(value);
},
});
Might be cleaner / simpler to use onItemAdd (see Usage page) to define a behavior when a new item is added. No need to change selectize.js for that, I think.

How do you post data to CouchDB both with and without using JavaScript

I have a show which displays a form with fields populated from a document. I'd like to change the values in the field and then save the updated document.
I'm having trouble finding a clear, concise example of how to do this.
Seriously, just finishing this example would work wonders for so many people (I'm going to leave a lot of stuff out to make this concise).
Install Couchapp
This is outside the scope of my question, but here are the instructions for completeness.
Create a couchapp
Again, this is kind outside the scope of my question. Here is a perfectly concise tutorial on how to create a couchapp.
Create a template
Create a folder in the root of your couchapp called templates. Within the templates folder create an HTML page called myname.html. Put the following in it.
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<form method='post' action='#'>
<fieldset>
Hello <input type='text' name='name' value='{{ name }}'>
<input type='submit' name='submit' value='submit'>
</form>
</body>
</html>
Create a show
See the tutorial above for hwo to do this.
Add this code to a show called myname.
function(doc, req) {
if (doc) {
var ddoc = this
var Mustache = require("vendor/couchapp/lib/mustache");
var data = {
title: "The Name",
name: "Bobbert"
}
return Mustache.to_html(ddoc.templates.myname, data)
} else {
return ('nothing here baby')
}
}
Update the document with a new name by ...
So who can complete this step via both the client side and the server side?
Please don't point me to the guide, I need to read it in your words.
Thanks.
Edit:
Although the return value isn't pretty, just posting a form to the update handler will update the document.
You will probably want to look into update handler functions.
An update handler handles granular document transformations. So you can take 1 form, that has one distinct purpose, and only update the relevant fields in your document via the update handler.
Your update handler will need to take a PUT request from your form. A browser can't do this directly, so you'll need some javascript to handle this for you. If you're using jQuery, this plugin can take your form and submit it seamlessly via AJAX using PUT for you.
Inside the function, you can take the fields you are accepting, in this case name and apply that directly to the document. (input validation can be handled via the validate_doc_update function)
Update Handler (in your Design Document)
{
"updates": {
"name": function (doc, req) {
doc.name = req.form.name;
return [doc, "Name has been updated"];
}
}
}
HTML
<form id="myForm" action="/db/_design/ddoc/_update/name/doc_id">...</form>
JavaScript
$(document).ready(function() {
$('#myForm').ajaxForm({
type: "PUT",
success: function () {
alert("Thank you");
}
});
});
Once you've gotten this basic example up and running, it's not much more difficult to add some more advanced features to your update handlers. :)

Drupal - Search box not working - custom theme template

I am using a customised version of search-theme-form.tpl
When I use the search box, I do get transferred to the search page. But the search does not actually take place. The search box on the search results page does work though. This is my search-them-form.tpl.php file (demo :
<input type="text" name="search_theme_form_keys" id="edit-search-theme-form-keys" value="Search" title="Enter the terms you wish to search for" class="logininput" height="24px" onblur="restoreSearch(this)" onfocus="clearInput(this)" />
<input type="submit" name="op" id="edit-submit" value="" class="form-submit" style="display: none;" />
<input type="hidden" name="form_token" id="edit-search-theme-form-form-token" value="<?php print drupal_get_token('search_theme_form'); ?>" />
<input type="hidden" name="form_id" id="edit-search-theme-form" value="search_theme_form" />
There is also a javascript file involved. I guess it's use is pretty clear from the code:
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
function clearInput(e) {
e.value=""; // clear default text when clicked
e.className="longininput_onfocus"; //change class
}
function restoreSearch(e) {
if (trim(e.value) == '') {
{
e.value="Search"; // reset default text onBlur
e.className="logininput"; //reset class
}
}
}
What can be the problem and how can I fix it?
Apparently, you cannot directly modify the HTML in search-theme-form.tpl.php since thats not the right way to do it. So my adding the class and onFocus and onBlur attributes was the problem.
The correct way to do it is to modify the themes template.php file. Basically we will be using form_alter() to modify the form elements. Since using the HTML way is wrong. Take a look at the code below (taken from : here )
<?php
/**
* Override or insert PHPTemplate variables into the search_theme_form template.
*
* #param $vars
* A sequential array of variables to pass to the theme template.
* #param $hook
* The name of the theme function being called (not used in this case.)
*/
function yourthemename_preprocess_search_theme_form(&$vars, $hook) {
// Note that in order to theme a search block you should rename this function
// to yourthemename_preprocess_search_block_form and use
// 'search_block_form' instead of 'search_theme_form' in the customizations
// bellow.
// Modify elements of the search form
$vars['form']['search_theme_form']['#title'] = t('');
// Set a default value for the search box
$vars['form']['search_theme_form']['#value'] = t('Search this Site');
// Add a custom class and placeholder text to the search box
$vars['form']['search_theme_form']['#attributes'] = array('class' => 'NormalTextBox txtSearch',
'onfocus' => "if (this.value == 'Search this Site') {this.value = '';}",
'onblur' => "if (this.value == '') {this.value = 'Search this Site';}");
// Change the text on the submit button
//$vars['form']['submit']['#value'] = t('Go');
// Rebuild the rendered version (search form only, rest remains unchanged)
unset($vars['form']['search_theme_form']['#printed']);
$vars['search']['search_theme_form'] = drupal_render($vars['form']['search_theme_form']);
$vars['form']['submit']['#type'] = 'image_button';
$vars['form']['submit']['#src'] = path_to_theme() . '/images/search.jpg';
// Rebuild the rendered version (submit button, rest remains unchanged)
unset($vars['form']['submit']['#printed']);
$vars['search']['submit'] = drupal_render($vars['form']['submit']);
// Collect all form elements to make it easier to print the whole form.
$vars['search_form'] = implode($vars['search']);
}
?>
In yourthemename_preprocess_search_theme_form - 'yourthemename' will obviously reflect the name of your custom theme. Basically the code is self-explanatory. what with the comments and all.
So, basically thats the way it works.

Resources