Cannot debug jQuery button - javascript

I have this button, and when clicked, it sends an ajax call which changes the value of score_up.
I dont see what the problem is. I tried firbug, but apparently it's not even detecting the javascript? :)) Thanks.
jquery:
$('.stats').delegate('.support', 'click', function(e) {
//stop event
e.preventDefault();
//get the id
var the_id = $(this).closest('.score').attr('id').split('_').pop();
//the main ajax request
$.ajax({
context:this,
type: "POST",
data: "action=support&id=" + the_id,
url: "ajax/sa.php",
success: function (msg) {
$(this).siblings("h2.score_up").html(msg).fadeIn();
//remove down button
// and remove support button
}
});
});
html:
<ul class="stats">
<li id="support_23"class="score">
<h2 class="score_up">12</h2>
<span style="text-align:center;">Supporters</span>
</li>
<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i>
<span>Support</span>
</button>
</li>
//vote down button
<li id="down_23"class="score">
<h2 class="score_down">12</h2>
<span style="text-align:center;">down</span>
</li>
<li>
<button type="submit" value="Actions" class="down" title="down">
<i></i>
<span>down</span>
</button>
</li>
</ul>

It is not valid HTML for a <button> to be a direct child of a <ul>.
Children of <ul> should be <li>. I wouldn't expect things to work properly with invalid HTML.
HTML with <button> inside a <li>:
<ul class="stats">
<li id="topic_23" class="score">
<h2 class="score_up">12</h2>
<span style="text-align:center;">Supporters</span>
</li>
<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i>
<span>Support</span>
</button>
</li>
</ul>
jQuery, fixing some of the traversal methods:
$('.stats').delegate('.support', 'click', function(e) {
//stop event
e.preventDefault();
// cache a reference to the previous <li> element
// since it is used more than once
var $prevLi = $(this).closest('li').prev('li');
//get the id
var the_id = $prevLi.attr('id').split('_').pop();
//the main ajax request
$.ajax({
context:this,
type: "POST",
data: "action=support&id=" + the_id,
url: "ajax/sa.php",
success: function (msg) {
$prevLi.find("h2.score_up").html(msg).fadeIn();
}
});
});

Your HTML is invalid, so I would do:
<form action="javascript:alert('form')";>
<ul class="stats">
<li id="topic_23"class="score">
<h2 class="score_up">12</h2>
<span style="text-align:center;">Supporters</span>
</li>
<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i><span>Support</span></button>
</li>
</ul>
</form>
And then the jQuery (which in your original would not work, since you wanted .siblings() and not .closest() would now be:
var the_id = $(this).closest("li").siblings('.score').attr('id')
.split('_').pop();
and success:
$(this).closest("li").siblings("li.score").find("h2.score_up")
.html(msg).fadeIn();
I think you also run into troubles with prevent default, since you want to prevent default on the form, and in that case you might run into problems with delegate.
Here is what I would do with .live():
// Prevent form from submitting
$("form").live("submit", function(e) {
e.preventDefault(); });
// Run Ajax
$('button.support').live('click', function(e) {
//get the id
var $score = $(this).closest("li").siblings('.score'),
the_id = $score.attr('id').split('_').pop();
//the main ajax request
$.ajax({
context:this,
type: "POST",
data: "action=support&id=" + the_id,
url: "ajax/sa.php",
success: function (msg) {
$score.find("h2.score_up").html(msg).fadeIn();
}
});
});
​
Try it out on this jsFiddle

Related

Combine/bind many on change, on click event of many tags with different id or class

In my view I have many tags with differents classed and ids like this:
<!-- html view -->
<div class="panel panel-default">
<ul class="" id="tablist" role="tablist">
<li class="getState active" id="proposed">
<b>Proposed</b>
</li>
<li class="getState" id="current">
<b>Current</b>
</li>
<li class="getState" id="incoming">
<b>Incoming</b>
</li>
<li class="getState" id="finished">
<b>Finished</b>
</li>
</ul>
</div>
<select class="form-control" id="isProduction">
<option value="" disabled selected>Type</option>
<option value="production">Production</option>
<option value="nonProduction">nonProduction</option>
</select>
<div>
<!-- some content here like <p></p> -->
<a href="#validity">
<button class="btn btn-default">Validity</button>
</a>
</div>
<div>
<!-- some content here like <p></p> -->
<a href="#rate">
<button class="btn btn-default">Rate</button>
</a>
</div>
<!-- content appear here -->
<div id="info">
<!-- put some content here following click and selected option change -->
</div>
Using jQuery, I would like to catch all clicks, changes of these tags, more precisely if user click on a <li></li> tag with class .getState, or if user have selected an option of the <select></select> tag which has the id #isProduction or if user have click on the other <button></button> tag wich have <a href="#validity"> or <a href="#rate">.
Like this example:
<script type="text/javascript" charset="utf-8" defer>
$('.getState').bind('click', function sortByState(){
var infoDiv = $('#info');
$.ajax({
type: "GET",
url: window.location.href,
data: {
state: $(this).attr("id"),
},
success: function(html){
infoDiv.empty();
var newinfoDiv = $(html).find('#info');
infoDiv.append(newinfoDiv);
infoDiv = newinfoDiv;
}
});
});
</script>
Here I could make a request (php server side) by recovering the state, then I could make a request with this argument.
How can I combine all these event in only one function in order to recover all the argument I need for my php server side using jQuery ?
I see on the doc here, that we could create a bind on multiple event like this:
$( "#foo" ).bind( "mouseenter mouseleave", function() {
$( this ).toggleClass( "entered" );
});
If I understand correctly you want to attach same event to multiple elements, if yes that could be done using comma separator ,:
$('body').on('click','#isProduction, .getState, button.my-btn',function(){
var infoDiv = $('#info');
$.ajax({
type: "GET",
url: window.location.href,
data: {
state: $(this).attr("id"),
},
success: function(html){
infoDiv.empty();
var newinfoDiv = $(html).find('#info');
infoDiv.append(newinfoDiv);
infoDiv = newinfoDiv;
}
});
})
NOTE : For the two buttons better if you could add a class to them so you will attach event just to them button.my-btn instead of attaching it to button so that will not infect other buttons click event.
<button class="btn btn-default my-btn">Validity</button>
<button class="btn btn-default my-btn">Rate</button>
Or also you could use separated function and attach events separately but trigger the same action :
$('body').on('click','.getState, button.my-btn',myAction);
$('body').on('change','#isProduction',myAction);
function myAction(){
var infoDiv = $('#info');
$.ajax({
type: "GET",
url: window.location.href,
data: {
state: $(this).attr("id"),
},
success: function(html){
infoDiv.empty();
var newinfoDiv = $(html).find('#info');
infoDiv.append(newinfoDiv);
infoDiv = newinfoDiv;
}
});
}
Hope this helps.
$('body').on('click','.getState, button.my-btn',myAction);
$('body').on('change','#isProduction',myAction);
function myAction(){
alert('myAction');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div class="panel panel-default">
<ul class="" id="tablist" role="tablist">
<li class="getState active" id="proposed">
<b>Proposed</b>
</li>
<li class="getState" id="current">
<b>Current</b>
</li>
<li class="getState" id="incoming">
<b>Incoming</b>
</li>
<li class="getState" id="finished">
<b>Finished</b>
</li>
</ul>
</div>
<select class="form-control" id="isProduction">
<option value="" disabled selected>Type</option>
<option value="production">Production</option>
<option value="nonProduction">nonProduction</option>
</select>
<div>
<!-- some content here like <p></p> -->
<a href="#validity">
<button class="btn btn-default my-btn">Validity</button>
</a>
</div>
<div>
<!-- some content here like <p></p> -->
<a href="#rate">
<button class="btn btn-default my-btn">Rate</button>
</a>
</div>
<!-- content appear here -->
<div id="info">
<!-- put some content here following click and selected option change -->
</div>
You can use below code to capture trigger click event on whole page and then you can write desired code to be executed:
$('body').bind('click',function(){
//your code here
});

How to populate Span elements in an Ajax success setting

After a form is submitted (form not shown) My page is receiving a JSON encoded array from my php script with no issue. The page has the following elements that I am trying to populate with the data from json. I'm trying to get the data to show up between the span elements.
<div class="added_display">
<ul>
<li>
<p>Title: <span class="title"></span></p>
</li>
<li style="color: #FF0004">
<p><span class="comment" style="color: #FF4245"></span></p>
</li>
<li>
<p>Address: <span class="address"></span></p>
</li>
<li>
<p>Sale Price: <span class="sale-price"></span></p>
</li>
<li>
<p>Lease Price: <span class="lease-price"></span></p>
</li>
<li>
<p>Lot Size: <span class="lot-size"></span></p>
</li>
<li>
<p>Building Size: <span class="building-size"></span></p>
</li>
<li>
<p>Zoning: <span class="zoning"></span></p>
</li>
</ul>
</div>
and the following ajax script directing everything. I am using the span elements class in the success setting:
$("document").ready(function() {
$(".data-form").submit(function() {
data = $(this).serialize();
if (confirm("Are you ready to sumbmit this listing?\nYou can always edit the listing after going to the menu tab - edit listing."))
{
$.ajax({
type: "POST",
dataType: "json",
url: "add-list.php",
data: data,
success: function(response) {
if (response.success) {
$("#modal1").modal('hide');
$(".added_display").show();
$(".title").data(title);
$(".comment").data(comment);
$(".address").data(address);
$(".sale-price").data(sale_price);
$(".lease-price").data(lease_price);
$(".lot-size").data(lot_size);
$(".building-size").data(build_size);
$(".zoning").data(zoning);
$(".ad_link").data(ad_link);
}
else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
error: function() {
alert("An Error has ocurred contacting the server. Please contact your system administrator");
}
});
return false;
}
});
});
I think my error is tied up in the success setting. How can I correct this code to populate my span elements?
Instead of .data(value); try .text(value);
The as per docs, .data() will store arbitrary data on an element. It won't be used to display a value in the DOM. If you want to set the text inside an element use .text(text).
If the values are HTML, use .html(htmlString).

Ajax change wrapper content

I'm trying to develop my skills with Ajax
I want to change my wrapper content with a different pages wrapper content without having to refresh the page.
I'm using:
$(function () {
$("#page2btn").click(function () {
$.ajax({
url: 'page2.asp',
data: { id: $(this).attr('id') },
success: function (data) {
$('#Wrapper').html(data);
}
});
});
});
<div id="Wrapper">
<div id="menu">
<a class="navbutton" onclick="MakeRequest1()">Home</a> <span class="navbutton">|</span>
<a class="navbutton" id="Page2btn">Page2</a> <span class="navbutton">|</span>
<a class="navbutton" onclick="MakeRequest3()">Page3</a>
</div>
<h1>Test1</h1>
</div>
and another page called page2.asp
with a different wrapper content saying Test2
But my wrapper wont change when I click the button.
any help would be appreciated.
Try to simplify it to determine if this is a problem with your front-end or back-end code...
Try this and see of it works any better..
$('#Wrapper').load('page2.asp?id='+$(this).attr('id'));
Try this:
$(function () {
$("#page2btn").click(function () {
$.ajax({
url: 'page2.asp',
data: { id: $(this).attr('id') },
success: function (data) {
$('#dynamic_content_div').html(data);//data = <h1>Test 2</h1>
}
});
});
});
HTML:
<div id="Wrapper">
<div id="menu">
<a class="navbutton" onclick="MakeRequest1()">Home</a> <span class="navbutton">|</span>
<a class="navbutton" id="Page2btn">Page2</a> <span class="navbutton">|</span>
<a class="navbutton" onclick="MakeRequest3()">Page3</a>
</div>
<div id="dynamic_content_div">
<h1>Test1</h1>
</div>
</div>
Javascript is case sensitive. You are using lowercase in case of assigning the event -
$(function () {
$("#page2btn").click(function () { //lowercase P
...
});
});
but using uppercase for html id
...
<a class="navbutton" id="Page2btn">Page2</a> <span class="navbutton">|</span> //upper case P
...
so, it never finds the item to bind to, thus nothing happens when you click. Either change js to -
$("#Page2btn").click(function ()
or change html to -
<a class="navbutton" id="page2btn">Page2</a> <span class="navbutton">|</span>
Other than this, I don't see the error.
Try jQuery replaceWith method, like this:
$(function () {
$("#page2btn").click(function () {
$.ajax({
url: 'page2.asp',
data: { id: $(this).attr('id') },
success: function (data) {
$("#Wrapper").replaceWith(data); //try with double qoutes
}
});
});
});
*The link below maybe helpful:
Change content of div using jQuery

Error in element count with Jquery due to click to update

I am counting the number of elements with span class check_box and uncheck_box When the item with check-box is clicked, its span change to uncheck-box and vice versa. The counter somewhat works, however, I need to click on an element first to trigger it (the count should have already have changed) and then when i click on an element the second time, the count changes. In this instance i should have got two counts but I only get one.
How can this be rectified?
HTML:
<span>All</span>
<span>Completed</span>
<span>Incomplete</span>
<ul class="leftlist">
<li class="todo" id="1011" itemage="1"><a href="javascript:;">
<a href="javascript:;" class="strike">
<span class="check_box cb"></span>
<p>Option 1 Complete</p> </a>
</li>
<li class="todo" id="1011" itemage="1"><a href="javascript:;">
<a href="javascript:;">
<span class="uncheck_box cb"></span>
<p>Option 1 Incomplete</p> </a>
</li>
<li class="todo" id="1011" itemage="1"><a href="javascript:;">
<a href="javascript:;" class="strike">
<span class="check_box cb"></span>
<p>Option 1 Complete</p> </a>
</li>
<li class="todo" id="1011" itemage="2"><a href="javascript:;">
<a href="javascript:;">
<span class="uncheck_box cb"></span>
<p>Option 2 InComplete</p> </a>
</li>
jQuery
var $checkboxes = jQuery('li.todo a'),
$completeCount = jQuery('.complete-count'),
$incompleteCount = jQuery('.incomplete-count');
var updateCount = function(){
$completeCount.text(jQuery('.check_box').length);
$incompleteCount.text(jQuery('.uncheck_box').length);
};
$checkboxes.on('click', updateCount);
updateCount();
Jquery that changes the elements
(function($){
$('li.todo').click(function(){
if($(this).find('.uncheck_box').length >0){
var _t=$(this).find('.uncheck_box');
_t.removeClass('uncheck_box');
_t.addClass('check_box');
m_val='1';
$(this).find('a').addClass('strike');
}else{
m_val='0';
var _t=$(this).find('.check_box');
_t.removeClass('check_box');
_t.addClass('uncheck_box');
$(this).find('a').removeClass('strike');
}
var m_key=jQuery(this).attr('id');
jQuery.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri(); ?>/ajax_get.php",
data: { meta_key: m_key, meta_value: m_val},
beforeSend: function( ) {
//jQuery(this).attr("disabled", true);
},
success:function(){}
})
});
The first problem here is the class change handler is registered to the li elements(making use of event bubbling) where as the counter handler is registered to the anchor element. So the anchor handler will get executed before the class is updated so attach the click handler to the li element instead of anchor element
var $checkboxes = jQuery('li.todo'),
$completeCount = jQuery('.complete-count'),
$incompleteCount = jQuery('.incomplete-count');
var updateCount = function(){
$completeCount.text(jQuery('.check_box').length);
$incompleteCount.text(jQuery('.uncheck_box').length);
};
$checkboxes.on('click', updateCount);
updateCount();
also make sure that this event handler is registered after the class change handler is registered
A better solution will be is to use a custom event which will be triggered once the class is changed
$('li.todo').click(function () {
if ($(this).find('.uncheck_box').length > 0) {
var _t = $(this).find('.uncheck_box');
_t.removeClass('uncheck_box');
_t.addClass('check_box');
m_val = '1';
$(this).find('a').addClass('strike');
} else {
m_val = '0';
var _t = $(this).find('.check_box');
_t.removeClass('check_box');
_t.addClass('uncheck_box');
$(this).find('a').removeClass('strike');
}
//trigger a custom event here
$(this).trigger('updateclass')
var m_key = jQuery(this).attr('id');
jQuery.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri(); ?>/ajax_get.php",
data: {
meta_key: m_key,
meta_value: m_val
},
beforeSend: function () {
//jQuery(this).attr("disabled", true);
},
success: function () {}
})
});
then the count handler will listen to the custom event instead of the click handler
var $checkboxes = jQuery('li.todo'),
$completeCount = jQuery('.complete-count'),
$incompleteCount = jQuery('.incomplete-count');
var updateCount = function(){
$completeCount.text(jQuery('.check_box').length);
$incompleteCount.text(jQuery('.uncheck_box').length);
};
$checkboxes.on('updateclass', updateCount);
updateCount();

Jquery on('click') not firing after first click

I have some HTML:
<div class="post-container self">
<a href="/user/Wiz">
<img class="avatar" alt="Profile Picture" src="">
</a>
<div class="post-body">
<div class="post" style="margin-left:0px;">
<div class="post-timestamp" style="display:inline-block;float:right">
Oct 31
</div>
<div class="post-functions dropdown displaynone" style="float:right;margin-right:5px;">
<a class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
<i class="icon-cog">
</i>
</a>
<ul class="dropdown-menu post-dropdown" role="menu" aria-labelledby="dLabel">
<a class="post-delete" href="javascript:void(0)"><i class="icon-trash"> </i>Delete</a>
</ul>
</div>
</div>
</div>
</div>
And with that, I have some Jquery:
$('.posts-content').on('click', '.post-delete', function(e) {
$('.post-dropdown').dropdown();
if (confirm('Are you sure you want to delete this post?')) {
var $this = $(this);
$.ajax({
url: '/a/delete_post',
type: 'POST',
dataType: 'json',
data: {'p' : post_id},
success: function() {
//...
return true;
}
});
}
return false;
});
Everything works perfectly the first click, but if I go to another post, and try to click .post-delete, the event never fires, and nothing shows up in the console. It also works if I use $.click(), but I need to dynamically create elements. Why does the $.on('click') not fire the second click?
My guess is that dropdown plugin you use change the DOM structure.
$('.post-dropdown').dropdown();
BTW,
$this.parent().parent().parent().parent().parent() this is really really bad practice.
You should use closest instead.
If you are dynamically creating elements try:
$(document).on('click', '.post-delete', function(e) { });

Categories

Resources