Button does not call function when clicked - javascript

I'd like a function t run when a button is clicked. It works fine when I approach it like so in the html body
<div type="button" id="decline" class="btn btn-danger mrs"></div>
However, I need it to work within the below code block, which is within a underscore.js wrapper. At the moment the function won't execute using the below, I'd like to understand why? is the id in the wrong place?
$('#containerFriendsPending').empty();
_.each(friends, function(item) {
var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
wrapper.append('<div type="button"
id="decline"
class="btn btn-danger mrs">' +
'Decline' +
'</div>');
$('#containerFriendsPending').append(wrapper);
});

While the code solution you posted will work the first time:
$('#decline').click(function() {
Friendrequest_decline();
});
It will not work after the wrapper code is replaced, as per your answer. You must use .on() to delegate the event:
$(document).on('click', '#decline', function() {
Friendrequest_decline();
});
or
$('#containerFriendsPending').on('click', '#decline', function() {
Friendrequest_decline();
});
Eg:
$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

Solved this myself.
The following needed to be added within the original question main code block
$('.decline').click(function() {
Friendrequest_decline();
});
So doing this works.
$('#containerFriendsPending').empty();
_.each(friends, function(item) {
var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
wrapper.append('<div type="button" id="decline" class="btn btn-danger mrs">' + 'Decline' + '</div>');
$('#containerFriendsPending').append(wrapper);
$('.decline').click(function() {
Friendrequest_decline();
});
});

As you didn't provide the code that launches the click event it's hard to debug, but I'm going to assume it's actually the most common mistake that causes this problem: You are binding the click event before the element actually exists. That way, the browser will not know the new element also needs the click event.
Example:
$('.test').click(someFunction);
$('body').append( $('<div class="test">Click me!</div>');
This will not work, because the click event is bound first and the element is created later.
The jQuery .on() function can handle that by also watching for new elements that are created in the DOM:
$('body').on('click', '.test', someFunction);
$('body').append( $('<div class="test">Click me!</div>');
Now it will run someFunction successfully.

Related

Element calling old action after class change [duplicate]

In my JSP page I added some links:
<a class="applicationdata" href="#" id="1">Organization Data</a>
<a class="applicationdata" href="#" id="2">Business Units</a>
<a class="applicationdata" href="#" id="6">Applications</a>
<a class="applicationdata" href="#" id="15">Data Entity</a>
It has a jQuery function registered for the click event:
$("a.applicationdata").click(function() {
var appid = $(this).attr("id");
$('#gentab a').addClass("tabclick");
$('#gentab a').attr('href', '#datacollector');
});
It will add a class, tabclick to <a> which is inside <li> with id="gentab". It is working fine. Here is my code for the <li>:
<li id="applndata"><a class="tabclick" href="#appdata" target="main">Application Data</a></li>
<li id="gentab">General</li>
Now I have a jQuery click handler for these links
$("a.tabclick").click(function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
For the first link it is working fine. It is alerting the <li> id. But for the second <li>, where the class="tabclick" is been added by first jQuery is not working.
I tried $("a.tabclick").live("click", function(), but then the first link click event was also not working.
Since the class is added dynamically, you need to use event delegation to register the event handler
$(document).on('click', "a.tabclick", function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
You should use the following:
$('#gentab').on('click', 'a.tabclick', function(event) {
event.preventDefault();
var liId = $(this).closest("li").attr("id");
alert(liId);
});
This will attach your event to any anchors within the #gentab element,
reducing the scope of having to check the whole document element tree and increasing efficiency.
.live() is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax
$(document).on('click', "a.tabclick", function() {
This syntax will work for delegated events
.on()
Based on #Arun P Johny this is how you do it for an input:
<input type="button" class="btEdit" id="myButton1">
This is how I got it in jQuery:
$(document).on('click', "input.btEdit", function () {
var id = this.id;
console.log(id);
});
This will log on the console: myButton1.
As #Arun said you need to add the event dinamically, but in my case you don't need to call the parent first.
UPDATE
Though it would be better to say:
$(document).on('click', "input.btEdit", function () {
var id = $(this).id;
console.log(id);
});
Since this is JQuery's syntax, even though both will work.
on document ready event there is no a tag with class tabclick. so you have to bind click event dynamically when you are adding tabclick class. please this code:
$("a.applicationdata").click(function() {
var appid = $(this).attr("id");
$('#gentab a').addClass("tabclick")
.click(function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
$('#gentab a').attr('href', '#datacollector');
});
Here is the another solution as well, the bind method.
$(document).bind('click', ".intro", function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
Cheers :)
I Know this is an old topic...but none of the above helped me.
And after searching a lot and trying everything...I came up with this.
First remove the click code out of the $(document).ready part and put it in a separate section.
then put your click code in an $(function(){......}); code.
Like this:
<script>
$(function(){
//your click code
$("a.tabclick").on('click',function() {
//do something
});
});
</script>

Combining / Refining two identical blocks of jQuery

I have two blocks of code that function exactly the same but need to fired independently in order to prevent overlap of functionality.
//Block One
jQuery('.top_searchicon').on('click touchstart', (function(e) {
e.preventDefault();
jQuery(this).toggleClass('active');
jQuery('.top_blog_search').toggleClass('active');
}));
//Block Two
jQuery('.searchicon').on('click touchstart', (function(e) {
e.preventDefault();
jQuery(this).toggleClass('active');
jQuery('.blog_search').toggleClass('active');
}));
Thank you very much.
You can combine selectors using a comma (,). You can then use is() and a ternary to choose the relevant element to set the active class on. Try this:
jQuery(function($) {
$('.top_searchicon, .searchicon').on('click touchstart', (function(e) {
e.preventDefault();
var $el = $(this).toggleClass('active');
var targetClass = $el.is('.searchicon') ? '.blog_search' : '.top_blog_search';
$(targetClass).toggleClass('active');
});
});
Note the use of the parameter in the ready handler, this enables you to still use the $ to reference jQuery within the scope of your document.ready handler.
An alternative to using the same event handler and checking within the event handler is to pass parameters to the event handler.
jQuery('.top_searchicon').on('click touchstart', function() {
handleClickTouchStart(".top_blog_search");
});
jQuery('.searchicon').on('click touchstart', function() {
handleClickTouchStart(".blog_search");
});
function handleClickTouchStart(selector)
{
e.preventDefault();
jQuery(this).toggleClass('active');
jQuery(selector).toggleClass('active');
}
This lets you add new handlers without needing to change the handler code (which would become quite messy with more than 2 options using .is (which is ofc fine if you only have 2, maybe 3)), eg:
jQuery('.another_searchicon').on('click touchstart', function() {
handleClickTouchStart(".another_blog_search");
});
The next step would be to use -data attributes to link the two.
This gives you the benefit of being able to add new elements without needing to change any code!
jQuery('.searchhandler').on('click touchstart', function() {
e.preventDefault();
jQuery(this).toggleClass('active');
var other = jQuery(this).data("related");
jQuery(other).toggleClass('active');
});
and change your markup to add matching -data (speculating on the markup here) :
<button type='button' class='searchhandler' data-related='.top_blog_search'>top search</button>
<button type='button' class='searchhandler' data-related='.blog_search'>blog search</button>
<div class='top_blog_search'></div>
...etc
to add another:
<button type='button' class='searchhandler' data-related='.another_search'>another search</button>
<div class='another_search'></div>

How can I set click function on my current element?

I am trying to dynamically set a click function on a role=button element I add from jQuery. Here is my code:
box_resources.forEach(function(box){
var title_button = '<a class="btn btn-primary btn-xs" style="margin:5px">' + title + '</a>';
var $list_item = $(title_button);
$list_item.click(function() {
console.log("hello");
});
$("#resources-master-list").append(title_button);
});
It seems this way does not work. Does anyone have any idea? Thanks!
Instead of adding a new click handler each time you add an item to the DOM, try using event delegation. To understand how this works, check out the link for more information.:
$(document).on("click", "[role='button']", function () {
alert("i'm clicked");
});

Document not detecting input value

I've had this problem for awhile now and I can't seem to fix it no matter what I do.
Basically, my input is not retrieving the value that the user types in the input for some reason..
Here is my code:
$('#aid').one('click', function () {
$('.prompt').prepend('<tr class="task"><td class="cell-icon"></td>' +
'<td class="cell-title"><div>User\'s Object: <input id="inputObject" type="text" style="margin-top: 2px;margin-left:2px"></input> Amount: <input id="inputAmount"' +
'type="text" style="margin-top:2px;margin-left:2px; padding-right: 0px"></input></div></td>' +
'<td class="cell-status hidden-phone hidden-tablet"><a class="btn btn-success" style="margin-top:3px">Submit</a></td>' +
'<td class="cell-time align-right">Just Now</td></div>' +
'</tr>');
});
$('.btn').click(function () {
console.log("click");
var input = document.getElementById('inputObject').value;
console.log(input);
});
Everything works fine including both clicks, but for some reason it just won't display the input value to the console.
I've also tried: $('#inputObject').val(); but that didn't work either.
I really hope that someone can help me here!
Another method: use delegate.
$('body').delegate('.btn', "click", function() {
var inp = document.getElementById("inputObject").value;
console.log(inp);
});
Explanation from http://www.w3schools.com/jquery/event_delegate.asp:
The delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur.
Event handlers attached using the delegate() method will work for both current and FUTURE elements (like a new element created by a script).
You are creating your HTML code dynamically so try using:
$(document).on("click",".btn", function(){
do stuff here...
});

getting id passed through a href link in click function

I've got a fairly straight forward question. Why can't I use $('a.view').attr('id') (Ref //1 in code) in my click function? I tried it and it failed to work but this.id works. I guess I primarily want to know the difference in the context of the code below:
displayRecord.php (The following link calls the click function):
echo '<td><a href="#" style="text-decoration: none;" id="'.$data['id'].'" class="view" ><input type="button" value="View" /></a></td>';
editTicket.php:
$('a.view').click(
function(e)
{
//1
var ticket_id = this.id;
dlg.load('displayRecord.php?id='+this.id, function(){
var escalationValue = '';
$.post('escalateValue.php',{post_ticket_id:ticket_id},
function(data) {
if (data == 'No'){
showCount();
}
});
dlg.dialog('open');
});
});
$('a.view').attr('id') can match multiple elements, if you have multiple anchors with a view class, so you will not necessarily get the clicked element if you use it within a click event. this.id refers only to the element that was clicked and would also be the fastest way, but to demonstrate you could also do:
$(this).attr('id'); // in the click event
This this, see if you are getting any alerts or not:
$(document).on('click', 'a.view', function(e) {
alert($(this).attr('id'));
alert(this.id);
});​

Categories

Resources