I have a connection to the Foursquare API in my application. The user can type in a box to start searching for venues, or they can click one of two venue links to fill the same select box with one of those two venues. I'm having trouble letting the user click one of either two venues in. Here is my code:
JS:
function venueFormatSelection(venue) {
if ( venue.name && venue.location.address ) {
// if a user starts typing into a box, venue.name and venue.address values will pop up for them to select from. OR in the 'else' case, they can click one of either two links
else {
$("#bigdrop_set").click(function () {
return $('#bigdrop_set').attr('venue_name')
})
$("#bigdrop_set_2").click(function () {
return $('#bigdrop_set_2').attr('venue_name_2')
})
}
}
HTML:
<span class="which_venue" id="bigdrop_set" venue_name='foo' venue_data='FOO'><%= link_to(FOOOOO) %></span>
<span class="which_venue" id="bigdrop_set_2" venue_name_2='bar' venue_data_2='BAR'><%= link_to(BARRRR) %></span>
For some reason, the "click to populate" JS only works if just ONE of the 'return' lines is included without the .click function:
return $('#bigdrop_set').attr('venue_name')
What's wrong with the code inside my "else" statement? Thanks!
$(".bigdrop_set").click(function () {
return $('#bigdrop_set').attr('venue_name')
})
Should be:
$("#bigdrop_set").click(function () {
return $('#bigdrop_set').attr('venue_name')
})
As you are selecting an element with the ID bigdrop_set not an element with the class bigdrop_set. ID's should be unique, in your code you have duplicate bigdrop_set ID's which should be changed.
Also I would suggest binding the click elements on the $(document).ready() function, not in the venueFormatSelection function.
Returning the value from the click function doesn't really make much sense either. Either manipulate the value directly in the function or put it in another function itself, not on the click event.
For example:
function alertVenue(venue) {
alert(venue)
}
$("#bigdrop_set").click(function () {
var venue = $('#bigdrop_set').attr('venue_name')
alertVenue(venue);
})
You have something like
$(".bigdrop_set").click(function () {
return $('#bigdrop_set').attr('venue_name')
})
Did you really mean css class selector .bigdrop_set and then id selector #bigdrop_set.
I found a fix by using a global variable. Doubt it's the cleanest approach, but it's working for now:
$("#bigdrop_set").click(function () {
window.clickVenue = $('#bigdrop_set').attr('venue_name');
$(".bigdrop").select2("val", $('#bigdrop_set').attr('venue_data'));
});
$("#bigdrop_set_2").click(function () {
window.clickVenue = $('#bigdrop_set_2').attr('venue_name_2');
$(".bigdrop").select2("val", $('#bigdrop_set_2').attr('venue_data_2'));
});
function venueFormatSelection(venue) {
if (venue.name && venue.location.address) {
var imageSource = venue.categories[0].icon.prefix.slice(0, -1) + venue.categories[0].icon.suffix;
return "<img src='" + imageSource + "' height='20' width='20' />" + " " + venue.name + " (" + venue.location.address + ")";
}
else {
return window.clickVenue;
}
}
Related
I have a variable that is attached to a function. I am trying to use that variable in an onclick event.
This is what I am doing
var show = function() {
console.log("hello");
};
$(container).append(
"<div class='info' onclick=" + show + ">Show</div>"
);
However the generated html comes out like this
<div class="info" onclick="function()" {="" console.log("hello");="" }="">
Show
</div>
Any idea how I can fix this so that when I click the div my function gets called ?
You can simply do like this, Just make show a function and call it on click.
This will work
<script>
function show() {
console.log("hello");
}
$(container).append(
'<div class="info" onclick="show()">Show</div>'
);
</script>
This is kind of an unusual approach to what you're trying to do. I think it would be more idiomatic in jQuery to either
a) define the element first, with event handler, and then append it,
$("<div>Show</div>", {
"class": "info",
on: {
click: function(e) {
console.log("Hello");
}
}
}).appendTo($(container));
or
b) append a new element and then add an event handler to it after appending it.
$(container).append("<div class='info'>Show</div>");
$(container).children('.info').last().on('click', function(e) { console.log("Hello"); });
Between those two, I'd recommend the first in this case.
The variable show is a function, Then how can you bind it with string?
The code should be like,
$(container).append("<div class='info' onClick='show()'>Show</div>");
try using :
var show = function() {
console.log("hello");
};
$(container).append("<div class='info' onclick="+'show()'+">Show</div>");
This will work.
The reason why your code
var show = function() {
console.log("hello");
};
$(container).append("<div class='info' onclick=" + show + ">Show</div>");
was not working as required as show is an object of type function, so when one uses the function name without the () the variable is replaced bu the code that it consists.
Hope it helps.
hey guys i am new to jquery and i was going throught the modal.js code and found the below code:
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
i tried to understand the above code , so i made a fiddle.
now if you see the if conditional in the code :
if ($this.is(':visible')) {
$('input').trigger('focus');
console.log($this + ' ' + 'is visible');
} else {
console.log($this + ' ' + 'invisible');
}
now even if i have the following display rule I.E.
input {
display:none;
}
The if condition still passes , well thats my 1st difficulty . why does the if condition pass ??
my secound difficulty is the line inside the if condition I.E.
$this.trigger('focus');
now even though the if condition passes the input does't get the focus . why ??
Thank you .
I've made some minor chances to your code, and now it all seems to work for me:
$(document).ready(function () {
$target = $('input');
$target.trigger('focus');
$target.one('show.bs.modal', function (showEvent) {
$this = $(this);
console.log($this);
if ($this.is(':visible')) {
$this.focus();
} else {
console.log($this + ' ' + 'invisible');
}
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
});
});
$target.trigger('show.bs.modal');
});
http://jsfiddle.net/v36zoy1g/2/
To focus an element, you don't need fancy code. the .focus() function does the job for you!
And actually, I think that's about it, can't remember anything else I changed to be honest. :p
You haven't cached $(this) on $this.
You can use:
$this = $(this) before you use $this in your code.
I am attempting to loop through a dynamic element and then print it with jquery,
Heres the code i use
$('.recipe-steps #addNewStep').on('click', function () {
var s = $('.recipe-steps .step').size() + 1;
$('<div class="step pure-u-1-1"><textarea id="step" name="step_detail[]" class="pure-u-1" placeholder="Step ' + s + '"></textarea>×</div>').appendTo($('.recipe-steps .steps'));
return false;
});
$(document).on('click', '.step .remove', function () {
$(this).parents('.step').remove();
return false;
});
however its only printing out the first element and not the preceding ones. I have created a fiddle can anyone see why?
http://jsfiddle.net/drk8X/
I wasn't able to come up with the perfect solution (will have a look later) but I have redesigned the function to work to an extent.
$("body").on('input propertychange', function () {
var outputme="";
$('textarea').each(function (index) {
outputme+='<br>'+(index+1) + '. ' + $(this).val();
});
$('#lp-step').html('<h3>Method</h3>'+outputme);
});
This will update the "preview" on change of the text area, use CSS Selectors to narrow down the scope, but id reccomend you looking at your HTML and try and simplify it a bit more.
http://jsfiddle.net/drk8X/2/
I have been making this form that must enable the back-end user to create new questions for users to answer. The form is cloned and appended to a div (selector #content) successfully after the first .on(click) event, but it won't duplicate the form again if the cloned button is pressed. The .on(change) event applied to my drop-down selection does change the content of respective divs like it is supposed to, but only on the original form.
Here's the JQuery code:
$(document).ready(function () {
$('.addAnswer').on("click", function () {
var idx = $('#mp div[name^="antwoord"]:last').index() + 1;
$clone = $('#mp div[name^="antwoord"]:first').clone(true, true).attr('class', 'answer content_' + idx);
$('.removeAnswer').show;
$('#mp').append($clone);
$('.answer:last').each(function () {
$('b:last').empty();
$('b:last').prepend(String.fromCharCode(64 + idx) + ". ")
$('.addAnswer').on("click", function () {
idx++;
});
});
if (idx == 2) {
$('.removeAnswer').show();
}
});
$('.nextq').click(function () {
var newqid = $('#content form:last').index() + 1;
$('.done, .nextq, .remove').hide();
$('#content').append('<hr>');
$('#content').append($('form').html()).attr('class', 'q_' + newqid);
$('.nextq').on("click", function () {
newqid++;
});
$('.done:last, .nextq:last, .remove:last').show();
return false;
});
$('.group').hide();
$('#text:last').show();
$('.select:last').on("change", function () {
$('.group').hide();
$('#' + $(this).val() + ':last').fadeIn();
$('button.' + $(this).val() + ':last').fadeIn();
});
});
Because I thought posting the whole HTML template would be a tad bit too much, I provided a JSFiddle for you people.
One extra question for the ones that are feeling kind: In the JQuery code it is seen that the contents of the HTML are being parsed using .html() and appended with .append.(Line 33 on the JSFiddle) As the .on(change) function switches the contents of the divisions it should change, .html() sees those changes and takes those along with it. I'd like the .on(click) function to append the div's content in its original state, unchanged by the changes made beforehand by the back-end user. Any help with this would be much obliged.
In order to have jQuery trigger on new elements you would do something like
$( document ).on( "click", "<your id or class>", function() {
//Do stuff
});
I'm having a slight issue getting a jquery action to function ideally. Currently everything is working properly on a blur from a particular field, which is called "person_email". The issue is that if the end user does this, and decides to click a hyperlink for example on the rest of the page that jquery from the blur triggers, the user see's this briefly, and then continues to the corresponding link.
Ideally this would work that the blur would only trigger if a hyperlink was not clicked.
var $email = $("#person_email");
var $hint = $("#hint_edit");
$email.on('blur',function() {
$hint.hide; // Hide the hint
$(this).mailcheck({
suggested: function(element, suggestion) {
// First error - Fill in/show entire hint element
var suggestion = "Did you mean: <span class='suggestion'>" +
"<span class='address'>" + "</span>" +
"<a href='#' class='domain'>" + suggestion.address +
"#" + suggestion.domain + "</a></span>?";
$hint.html(suggestion).fadeIn(150);
}
});
});
$hint.on('click', '.domain', function() {
// On click, fill in the field with the suggestion and remove the hint
$email.val($(".suggestion").text());
$hint.fadeOut(200, function() {
$(this).empty();
});
return false;
});
})
I assume you want off
$("a").on("click",function() {
$email.off();
});