Jquery not firing inside handlebars template - javascript

I have Javascript directory search that uses jquery and jquery UI code that works on it's own page but as soon as I use the handlebars templates, the on submit function isn't registering or firing anything:
$(".navbar-form").submit(function () {
var a = $("#searchFullName").val();
var currentTab = '';
$('li.active').each(function(index) {
currentTab = $(this).find('a').html();
});
getFirstAndLastName(a);
if(currentTab == 'Student')
callStudentWebService();
if(currentTab == 'Faculty/Staff')
callStaffWebService();
$('#searchFullName').blur();
return false;
});
HTML and JS pasted here:
http://jsfiddle.net/5Cr9s/
Is it possible to reload the Javascript file(s) when a template changes in handlebars? I'm really stuck here.

Thanks so much charlietfl!
$( "body" ).delegate( "form", "submit", function() {
...
This worked like a charm!

This worked in my case where I use select with event delegation
$("body").delegate('select[name="carType"]', 'change',function () {
var selectedOption = $("option:selected", this);
var val = this.value;
});

Related

Jquery .change() event fires only once

So I'm fairly novice with jquery and js, so I apologise if this is a stupid error but after researching I can't figure it out.
So I have a list of data loaded initially in a template, one part of which is a dropdown box that lets you filter the data. My issue is that the filtering only works once? As in, the .change function inside $(document).ready() only fires the once.
There are two ways to reload the data, either click the logo and reload it all, or use the search bar. Doing either of these at any time also means the .change function never fires again. Not until you refresh the page.
var list_template, article_template, modal_template;
var current_article = list.heroes[0];
function showTemplate(template, data)
{
var html = template(data);
$("#content").html(html);
}
$(document).ready(function()
{
var source = $("#list-template").html();
list_template = Handlebars.compile(source);
source = $("#article-template").html();
article_template = Handlebars.compile(source);
source = $("#modal-template").html();
modal_template = Handlebars.compile(source);
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
$("#classFilter").change(function()
{
console.log("WOW!");
var classToFilter = this.value;
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.heroClass.search(classToFilter) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
$("#searchbox").keypress(function (e)
{
if(e.which == 13)
{
var rawSearchText = $('#searchbox').val();
var search_text = rawSearchText.toLowerCase();
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.name.search(search_text) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
}
});
$("#logo").click(function()
{
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
//$("#logo").click();
});
function displayModal(event)
{
var imageNumber = $(this).data("id");
console.log(imageNumber);
var html = modal_template(current_article.article[0].vicPose[imageNumber]);
$('#modal-container').html(html);
$("#imageModal").modal('show');
}
I should note two things: first, that the search bar works perfectly, and the anonymous function inside both of them is nearly identical, and like I said, the filtering works perfectly if you try it after the initial load. The second is that the same problem occurs replacing .change(anonymous function) with .on("change",anonymous function)
Any help or advice would be greatly appreciated. Thanks.
I agree with Fernando Urban's answer, but it doesn't actually explain what's going on.
You've created a handler attached to an HTML element (id="classFilter") which causes part of the HTML to be rewritten. I suspect that the handler overwrites the HTML which contains the element with the handler on it. So after this the user is clicking on a new HTML element, which looks like the old one but doesn't have a handler.
There are two ways round this. You could add code inside the handler which adds the handler to the new element which has just been created. In this case, that would mean making the handler a named function which refers to itself. Or (the easier way) you could do what Fernando did. If you do this, the event handler is attached to the body, but it only responds to clicks on the #classFilter element inside the body. In other words, when the user clicks anywhere on the body, jQuery checks whether the click happened on a body #classFilter element. This way, it doesn't matter whether the #classFilter existed when the handler was set. See "Direct and delegated events" in jQuery docs for .on method.
Try to use some reference like 'body' in the event listeners inside your DOM like:
$('body').on('click','.articleButton', function() {
//Do your stuff...
})
$('body').on('click','#classFilter', function() {
//Do your stuff...
})
$('body').on('keypress','#searchbox', function() {
//Do your stuff...
})
$('body').on('click','#logo', function() {
//Do your stuff...
})
This will work that you can fire it more than once.

pass value/variable from fancybox iframe to parent

I'am trying to pass a variable/ value from the fancybox iframe to the parent window without success.
Fancybox is launched from a link with
class="fancybox fancybox.iframe"
My code in the fancybox.iframe is:
$(document).ready(function(){
$('.insert_single').click(function(){
var test = $('.members_body').find('{row.U_USERNAME}');
setTimeout(function(){ parent.$.fancybox.close();},300);return true;
});
});
Where '{row.U_USERNAME}' is the username to find in the iframe.
Then, in the parent there's the following code:
$(document).ready(function(){
$('.fancybox').fancybox(
{
openEffect:'fade',
openSpeed:500,
afterClose: function(){
alert($(".fancybox-iframe").contents().find(test));
$('#form input[name=username]').val()(test);return false;
}
}
);
});
But when the fancybox is closed, there's no alert showing up with the variable "test", nor the variable is showing up as a value or as a text in the input field of the form.
I've read and tried various solutions found here on stackoverflow without success.
Thanks in advance for helping
EDIT
Here's an Example
When the fancybox is closed the iframe is removed from the document. So you must use beforeClose event instead of afterClose
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500,
beforeClose: function() {
// working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
},
afterClose: function() {
// not working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
}
});
});
JSFiddle: http://jsfiddle.net/NXY7Y/1/
EDIT:
I edited your jsfiddle (http://jsfiddle.net/NXY7Y/9/). Update is in this link
http://jsfiddle.net/NXY7Y/13/
Main page javscript:
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500//,
//beforeClose: function() {
// // working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//},
//afterClose: function() {
// // not working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//}
});
});
function setSelectedUser(userText) {
$('#username').val(userText);
}
No need to use afterClose or beforeClose events. Just access the parent function setSelectedUser from the iframe on link click event like this:
$(document).ready(function() {
$('a.insert_single').click(function() {
parent.setSelectedUser($(this).text());
parent.$.fancybox.close();
});
});
Some clarifications :
You should use .find() to find elements by selector (you are trying to find a variable .find(test), which is not a valid format).
You should use .val() to get the contents of an input field or .val(new_value) to set the contents of an input field
You should use .html() or .text() to get the contents of any element other than input,
example: having this html code
<p class="test">hola</p>
... and this jQuery code
var temp = $(".test").html();
... temp will return hola.
On the other hand, if you have control over the iframed page and it's under the same domain than the parent page, then you may not need to set any jQuery in the child page.
so, having this html in the child (iframed) page for instance
<div class="members_body">
<p>GOOGLE</p>
<p>JSFIDDLE</p>
<p>STACKOVERFLOW</p>
</div>
You could set this jQuery in your parent page to get the contents of any clicked element in your child page :
var _tmpvar; // the var to use through the callbacks
jQuery(document).ready(function ($) {
$(".fancybox").fancybox({
type: "iframe",
afterShow: function () {
var $iframe = $('.fancybox-iframe');
$iframe.contents().find(".members_body p").each(function (i) {
$(this).on("click", function () {
_tmpvar = $('.members_body p:eq(' + i + ')', $iframe.contents()).html();
$.fancybox.close();
}); // on click
}); // each
},
afterClose: function () {
$('#form input[name=username]').val(_tmpvar);
}
});
}); // ready
Notice that we declared the var _tmpvar globally so we can use it within different callbacks.
See JSFIDDLE

.on() jQuery function not working after page updated via AJAX

This code essentially shows hidden content and reassigns a new button when it does the function.
The problem I am having is that when pagination is selected, or the price slider is selected/used, the function is not readied again.
My jQuery .on() code works fine in the fiddle (http://jsfiddle.net/hslincoln/Fgx7D/4/) but not in the test environment (http://jmldirect.uat.venda.com/uk/offers/icat/7offers):
HTML:
<img class="brands-toggle" id="#brandresults" src="http://jmldirect.uat.venda.com/content/ebiz/shop/resources/images/+.png">
jQuery:
jQuery(".brands-toggle").bind( "click", function() {
var collapse_content_selector = jQuery(this).attr('id');
var toggle_switch = jQuery(this);
jQuery(collapse_content_selector).toggle(function () {
if (jQuery(this).css('display') == 'none') {
toggle_switch.attr("src", toggle_switch.attr("src").replace("http://jmldirect.uat.venda.com/content/ebiz/shop/resources/images/-.png","http://jmldirect.uat.venda.com/content/ebiz/shop/resources/images/+.png"));
} else {
toggle_switch.attr("src", toggle_switch.attr("src").replace("http://jmldirect.uat.venda.com/content/ebiz/shop/resources/images/+.png", "http://jmldirect.uat.venda.com/content/ebiz/shop/resources/images/-.png"));
}
});
});
Any suggestions?
EDIT:
Changed the syntax to work with earlier version of jQuery - use of .bind() instead of .on().
Still the problem with it not reloading after AJAX call.
This was cleared up and .delegate() was a more appropriate method:
jQuery:
// 1.1 Brands toggle
jQuery(".wpShadow").delegate( ".boxContent #brand", "click", function(e) {
e.preventDefault();
var collapse_content_selector = jQuery('#brandresults');
var toggle_switch = jQuery(this).find('img');
if (jQuery(collapse_content_selector).css('display') == 'none') {
toggle_switch.attr("src", toggle_switch.attr("src").replace("bkg-dropdown.png","bkg-dropdown-minus.png"));
} else {
toggle_switch.attr("src", toggle_switch.attr("src").replace("bkg-dropdown-minus.png", "bkg-dropdown.png"));
}
jQuery(collapse_content_selector).toggle();
});
Try $('body').on instead of $(document)/on

jquery .live to .on in jquery upgrade

I'm upgrading the jQuery on my website to jQuery v1.10.1 from 1.4.2 .
I'm changing all the .live functions to .on.
Now i'm having trouble with changing one of them.
function tb_init(domChunk){
$(domChunk).live('click', function(){
var t = this.title || this.name || null;
var c = $(this).parent().parent().find('.quotation').html();
var a = this.href || this.alt;
var g = this.rel || false;
var o = $(this);
tb_show2(t,c,a,g,o);
this.blur();
return false;
});
}
I tried changing it to:
$(document).on("click", domChunk, function() {
and:
$(document).on("click", $(domChunk), function() {
But both don't seem to work. domChunk itself is a selector like this: "#myid li"
The error I get is: Uncaught TypeError: Object # has no method 'blur'
Thanks
this is a reference to the DOM object and not to the jQuery object.
Try this instead:
$(this).blur();
or:
$(this).trigger('blur');
or in your code use o instead of $(this)
I could be wrong, but have you tried using $(this).blur() instead of this.blur? Since it is a jQuery function...
edit: sorry I hadn't refreshed the page before answering

custom jquery selector attributes is not firing in emulator

live event is not firing in emulator(mobile,tab), it is working in browser
$("[data-bind]").live("touchstart", function(e) {
alert("hi");
});
this is my code...
You can apply the selector to the DOM elements only. You used the [data-bind].
Try like this
$("#id").on("touchstart", function (e) {
var data = $(this).attr('data-bind').val();
var view = this;
var url = $(e.currentTarget).attr('title');
app_router.navigate(url, {
trigger: true
});
});

Categories

Resources