If..else statement based off array function results - javascript

What I want to happen is to have different URLs be provided based of what the array function result is.
Basically, if collectTags is equal to "church" or "concert" it links to A.com else it links to B.com.
Here's the code I currently have:
caption : function( instance, item ) {
var caption, link, collectTags, tags;
caption = $(this).data('caption');
link = 'Download image';
collectTags = $(this).parent().attr("class").split(' ');
tags = $.map(collectTags,function(it){ if(collectTags === "church"){ return ''+ it +''} else{return ''+ it +''};});
return (caption ? caption + '<br />' : '') + link + '<br/>' + tags.slice(1);
}

I'm not sure that I can do it right, but I'll give it a try. Your problem is that you access collectTags again. That is an array, not a string, so you comparing it to a string will always be false. And never to use string concatination that will make your code harder to read & mess.
{
caption: function (instance, item) {
var caption, link, collectTags, tags;
function format(tpl, binding) {
if (typeof binding != 'function') return format(tpl, function (_, name) {
return binding[name];
});
return tpl.replace(/\$(\w+)/g, binding);
}
caption = $(this).data('caption');
link = format('Download image', item);
collectTags = $(this).parent().attr("class").split(' ');
function createTag(it) {
return format("<a href='$site/$it'>$it</a>", {
site: (it == 'church' || it == 'concert') ? 'A.com' : 'B.com',
it: it
});
}
tags = $.map(collectTags, createTag);
return [].concat(caption ? [caption, link] : link).concat(tags).join('<br/>');
}
}

Related

Boostrap popover not working with html injection

I'm trying to create dynamic popovers that are generated from a 'dictionary' array that injects HTML into existing text on the page. The code was initially uses for tooltips and worked well but now I am trying to transfer over to popovers. However the html isn't injecting and I'm stuck with it. The aim is to click on a word and have the definition etc popup. I also have a standard popover on the same page that functions correctly. I'm not getting any errors in the console :(
//script.js
$(function() {
var $words = [
{
word: "ね",
kana: "",
romaji: "ne",
definition: "n postposition<br>indicates emphasis, agreement, request for confirmation, etc., is it so, hey, come on, listen, not",
note: ""
},
{
word: " 動画",
kana: "どうが",
romaji: "douga",
definition: "video, movie, moving picture, animation, animated cartoon, in-betweens (animation)",
note: ""
},
{
word: " 今日",
kana: "きょう",
romaji: "kyou",
definition: "adjective today, this day, these days, recently, nowadays",
note: ""
},
{
word: "毎日",
kana: "まいにち",
romaji: "mainichi",
definition: "every day",
note: ""
},
{
word: "も",
kana: "",
romaji: "mo",
definition: "adjective today, this day, these days, recently, nowadays",
note: " te form"
},
{
word: "頑張りましょう",
kana: "がんばりましょう",
romaji: "ganbarimashou",
definition: "verb to persevere, to persist, to keep at it, to hang on, to hold out, to do one\'s best",
note: "lets do"
},
];
$('.define').definitions({
term: $words
});
}); //end $(function()
$(document).ready(function() {
$('[data-toggle="popover"]').popover();
});
/*==================js/jquery.define.js============================*/
var html;
$.fn.definitions = function(words) {
//$.fn alias for jQuery.prototype extends jQuery with your own functions
//console.log("words: ", words); // returns words array
var count = 0;
// Iterate over a jQuery object, executing a function for each matched element.
return this.each(function() {
var _results = [];
var _term = words["term"]; //console.log(_term); //return each definition / word pair object in a single array
var _this = $(this); //console.log(_this);
if (_term.length > 1) {
$.each(_term, function() {
for (let key in _term) {
// iterates over all properties of an object returning value only.
var val = _term[key]; //console.log(val); //returns each dict def / word pair object individually
_results.push(
_this.html(function(index, htmlContent) {
if (
_this
.text()
.toUpperCase()
.indexOf(val["word"].toUpperCase()) >= 0
) {
//console.log(html);
return (html = define_replace(
val["word"],
val["definition"],
val["kana"],
val["romaji"],
val["note"],
htmlContent,
key
)); //html injecting
}
})
);
} //end for...in
});
$("#japanese").html(html); //changed from .text()
} else {
_results.push(
_this.html(function(index, htmlContent) {
if (
_this
.text()
.toUpperCase()
.indexOf(_term["word"].toUpperCase()) >= 0
) {
return (html = define_replace(
_term["word"],
_term["definition"],
_term["kana"],
_term["romaji"],
htmlContent
));
}
})
);
}
}); //end return this.each(function()
}; //end $.fn.definitions
//inject class before and after found word in html
var define_replace = function(word, def, kan, rom, note, html, key) {
//console.log(arguments);
return html.replace(
'<a data-html="true" data-toggle="popover" title="Popover - title" data-content="' + def + '>' + word + " " + '</a>', "gi"
); //html building - replace word + space with html
(n - adv, n, ctr) time;
hours;
(P) < /span></span >
}; // end define_replace
//index.html
<div class="define">
<p id="japanese">ね 、 毎日 動画 今日 も 頑張りましょう</p>
</div>
include popper.min.js before bootstrap.js or use bootstrap.bundle.min.js and Enable popovers everywhere
$(function () {
$('[data-toggle="popover"]').popover()
})

Kendo Grid - Window template button with update functionality

Right now I am using a window to view details that are not shown in the grid. I have made my own custom editor in the window as well which hides the details and replaces them with inputs.
Unfortunately I cannot get the Update button to have the same functionality as an update button in the kendo toolbar.
I am using transport and parameter map for my create which works perfectly. I just need to be able to hit the update, which I haven't been able to.
Here is a snippet of code for the template:
<li><b>Change Control Objective</b></li>
<li><textarea type="text" class="k-textbox k-input" data-bind="value:ChangeControlObjective">#= ChangeControlObjective #</textarea></li>
<li><b>Change Control Specifics</b></li>
<li><textarea type="text" class="k-textbox k-input" data-bind="value:ChangeControlSpecifics">#= ChangeControlSpecifics #</textarea></li>
<span class="k-update k-icon k-i-tick"></span>Save
I can't show my JS code but it is based off this dojo: http://dojo.telerik.com/abUHI
UPDATE:
I am able to hit the update in the parametermap off of my save button click but it's sending the old data to the update instead of the new. Here is the button click code:
$("#saveChanges").click(function () {
dataItem.dirty = true;
$("#ccrGrid").data('kendoGrid').saveChanges();
});
Each input has a data-bind attribute and the parametermap looks like this:
case "update":
var changeControlRequestId = options.ChangeControlRequestID;
var changeControlObjective = options.ChangeControlObjective;
var changeControlSpecifics = options.ChangeControlSpecifics;
var productAssociation;
if (options.AccountChangeInfo.ProductAssocation == undefined) {
productAssociation = "";
} else { productAssociation = options.ProductAssocation; }
var amortization;
if (options.AccountChangeInfo.Amortization == undefined) {
amortization = "";
} else { amortization = options.Amortization; }
var productType;
if (options.ProductChangeInfo.ProductType == undefined) {
productType = "";
} else { productType = options.ProductType; }
var productName;
if (options.ProductChangeInfo.ProductName == undefined) {
productName = "";
} else { productName = options.ProductName; }
var productDescription;
if (options.ProductChangeInfo.ProductDescription == undefined) {
productDescription = "";
} else { productDescription = options.ProductDescription; }
var productContract;
if (options.ProductChangeInfo.ProductContractualFeatures == undefined) {
productContract = "";
} else { productContract = options.ProductContractualFeatures; }
var productBehavior;
if (options.ProductChangeInfo.ProductBehavioralAssumptions == undefined) {
productBehavior = "";
} else { productBehavior = options.ProductBehavioralAssumptions; }
var evaluationBehavior;
if (options.ProductChangeInfo.ProductEvaluationBehavior == undefined) {
evaluationBehavior = "";
} else { evaluationBehavior = options.ProductEvaluationBehavior; }
var productStratification;
if (options.ProductChangeInfo.ProductStratificationRoutines == undefined) {
productStratification = "";
} else { productStratification = options.ProductStratificationRoutines; }
if (content.isreadonly == "True") {
alert("you have readonly access");
}
else {
var urlString = "env=" + content.env + "&allyid=" + content.userId + "&changeRequestID" + changeRequestID + "&changeControlObjective=" + changeControlObjective + "&changeControlSpecifics=" + changeControlSpecifics +
"&productAssociation" + productAssociation + "&amortization" + amortization +
"&productType" + productType + "&productName" + productName + "&productDescription" + productDescription +
"&productContract" + productContract + "&productBehavior" + productBehavior + "&evaluationBehavior" + evaluationBehavior +
"&productStratification" + productStratification;
return urlString;
I've been going through this a couple months ago. Per my extensive research there are 2 key sources for doing custom popup editing in Kendo in entire Internet ;) :
Custom editor template
I aslo created a simplified version of this for you here: http://jsbin.com/qudotag/
to cut the elements which can be expanded once you grap the key concepts. Note that this does not work fully as changes are not persisted. It is expected behaviour, as you would need to define the CRUD operations for the grid (what happens when save, cancel etc. is done).
How to deal with CRUD is available in the second source:
Crud with external form
Some heavy studying of these 2 along with going into some more depths of MVVM (which might be intimidating at first, but then really useful for much smoother work with Kendo) will get you going.
Edit: actually you could do with just first approach, which is easier and retain the state by refreshing the grid after cancel.

JSON List ASP.net MVC

I have /Views/Movies/Index.cshtml with
<input type="button" id="getmoviex" value="Get moviex" />
<ul id="moviex_list"/>
<p>
Title: #Html.TextBox("SearchTitle") <br />
</p>
I have /Controllers/MoviesController.cs with
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult moviex(string SearchGenre, string SearchTitle, string SearchActor)
{
var db = new CinemaContext();
db.Configuration.ProxyCreationEnabled = false;
var Movie = from m in db.Movie
select m;
if (!String.IsNullOrEmpty(SearchTitle))
{
Movie = Movie.Where(s => s.Title.Contains(SearchTitle));
}
return Json(db.Movie.ToList(), JsonRequestBehavior.AllowGet);
}
I have Javascript.js with
$(document).ready(function () {
$('#getmoviex').click(function () {
$.getJSON("/Movies", null, getmoviex);
});
});
Have I correctly written /Movies? Or this should be /Views/Movies?
function getmoviex(moviex) {
$("#moviex_list").text("");
$.each(moviex, function (i) {
$("#moviex_list").append("<li>" + this + "</li>");
});
}
How can I display info or list info from my query? Or view some output with error?
First make sure you button click does not trigger a request to server. Preventing default behavior is a standard way of doing it:
$('#getmoviex').click(function (event) {
$.getJSON("/Movies", null, getmoviex);
event.preventDefault();
});
As for the URL, it should not be to view, but to action instead. Your action is moviex and controller is Movies, so
$.getJSON("/Movies/moviex", null, getmoviex);
The rest looks fine, so that should do it.
you need to pass your arguments as well in url (GET).
Something like this could work:
$('#getmoviex').click(function(event) {
event.preventDefault();
$.getJSON("/Movies/moviex?SearchGenre=yuorgenre&SearchTitle=Cal&SearchActor=youractor", function(moviex) {
var lis;
//please check the console
console.log(moviex);
$.each(moviex, function(b) {
lis += "<li id='" + b.Id + "'>" + b.Title + "</li>");
}); document.getElementById("moviex_list").innerHTML += lis;
});
});
To avoid circular reference in Serializing you may use:
if (String.IsNullOrEmpty(SearchTitle)) {
return View("Error");
}
var db = new CinemaContext();
var Movie = (from m in db.Movie
Where m.Title.Contains(SearchTitle)
select new {
Id = m.MovieID,
Title = m.Title // can add more properties
}).ToList();
return Json(Movie, JsonRequestBehavior.AllowGet);

Alternate code for "if else" in my code

Below given was my javaScript code.
Condition is, If I give a word like hello. the image for a hello should be displayed or if I give facebook, the image for that has to be displayed likewise for many words, the mentioned image has to be displayed.. But here in my code condition gets failed after first time and image is not displaying for the second word.
Help me with the alternate code for the above mentioned problem
var anu = document.getElementById("display");
var a= document.getElementById("final_span").textContent;
console.log(linebreak(interim_transcript));
if(a.search("hello") || a.search("facebook")){
if(linebreak(interim_transcript) == "hello"){
anu.innerHTML="<img src=hello.jpg>";
}
else if(linebreak(interim_transcript) == "facebook"){
anu.innerHTML="<img src=facebook.jpg>";
}
else if(linebreak(interim_transcript) == "hi"){
anu.innerHTML="<img src=hi.jpg>";
}
else if(linebreak(interim_transcript) == "doll"){
anu.innerHTML="<img src=doll.jpg>";
}
If the value returned by linebreak and image name are same you can use
anu.innerHTML = '<img src="' + linebreak(interim_transcript) + '">';
Otherwise you can use a object where you can specify the image name
var obj = {
hello: "hello.jpg",
facebook: 'facebook.jpg',
hi: 'hi.jpg'
}
var anu = document.getElementById("display");
var a = document.getElementById("final_span").textContent;
if (a.search("hello") || a.search("facebook")) {
var lb = linebreak(interim_transcript);
if (obj[lb]) {
anu.innerHTML = '<img src="' + obj[lb] + '">';
}
}

Regex replace url with links

I need a little help with some regex I have. Basically I have a shout box that only shows text. I would like to replace urls with links and image urls with the image. I've got the basics working, it just when I try to name a link that I have problems, well if there is more than one link... check out the demo.
Named link format {name}:url should become name. The problem I am having is with shout #5 where the regex doesn't split the two urls properly.
HTML
<ul>
<li>Shout #1 and a link to google: http://www.google.com</li>
<li>Shout #2 with an image: http://i201.photobucket.com/albums/aa236/Mottie1/SMRT.jpg</li>
<li>Shout #3 with two links: http://www.google.com and http://www.yahoo.com</li>
<li>Shout #4 with named link: {google}:http://www.google.com</li>
<li>Shout #5 with two named links: {google}:http://www.google.com and {yahoo}:http://www.yahoo.com and {google}:http://www.google.com</li>
</ul>
Script
var rex1 = /(\{(.+)\}:)?(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g,
rex2 = /(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g;
$('ul li').each(function(i){
var shout = $(this);
shout.html(function(i,h){
var p = h.split(rex1),
img = h.match(rex2),
typ = (p[2] !== '') ? '$2' : 'link';
if (img !== null) {
shout.addClass('shoutWithImage')
typ = '<img src="' + img + '" alt="" />';
}
return h.replace(rex1, typ);
});
});
Update: I figured it out thanks to Brad helping me with the regex. In case anyone needs it, here is the updated demo and code (Now works in IE!!):
var rex1 = /(\{(.+?)\}:)?(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g,
rex2 = /(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g;
$('ul li').each(function(i) {
var shout = $(this);
shout.html(function(i, h) {
var txt, url = h.split(' '),
img = h.match(rex2);
if (img !== null) {
shout.addClass('shoutWithImage');
$.each(img, function(i, image) {
h = h.replace(image, '<img src="' + image + '" alt="" />');
});
} else {
$.each(url, function(i, u) {
if (rex1.test(u)) {
txt = u.split(':')[0] || ' ';
if (txt.indexOf('{') >= 0) {
u = u.replace(txt + ':', '');
txt = txt.replace(/[\{\}]/g, '');
} else {
txt = '';
}
url[i] = '' + ((txt == '') ? 'link' : txt) + '';
}
});
h = url.join(' ');
}
return h;
});
});
(\{(.+?)\}:)
you need the ? to make the regex become "ungreedy" and not just find the next brace.
EDIT
However, if you remove the {yahoo}: the second link becomes null too (seems to populate the anchor tag, just no attribute within). This almost seems to be a victim of using a split instead of a replace. I would almost recommend doing a once-over looking for links first, then go back around looking for images (I don't see any harm in off-linking directly to the image, unless that's not a desired result?)

Categories