I have the following HTML:
<a class="btn test-btn test-btn-1">
<span>Content 1</span>
</a>
This is used multiple times on the page. The 1 at the end of the test-btn- is generated dynamically so it could be 1 or it could be 200.
When the button is clicked some AJAX runs and a class gets added to the a tag called test-btn-clicked. When it's all finished I want to update the content within the span to say something different.
Now I've tried a few ways but everytime it keeps updating the content of every button and not just the one I have clicked.
Can anyone suggest a way to do this?
You need to target the current clicked element only, however you wont be able to access $(this) in ajax call as the context will be changed from clicked element to ajax call. You should define the current elements context before ajax call and then use it to update the clicked element. something like this:
$('.test-btn').click(function(){
var that = this;
$.ajax( { url: '#',success: function (result) {
$(that).find('span').text("new span text here");
});
});
Assuming this is the function that triggers the ajax call:
$('.btn').on('click', function() {
var that = $(this);
that.addClass('test-btn-clicked');
$.ajax({
url: "test.html"
}).done(function(data) {
that.find('span').html(data);
});
});
you need to do use this like
$('.test-btn').click(function(){ //
// your code
$(this).find('span').text('some text');
});
Related
I have a script for deleting a record without refreshing. I'm still new to javascript and trying to learn how to call out this script. Here's what I have.
My button:
<button id="<?php echo $rrr['id']; ?>" class="delbutton" onclick="">Delete</button>
My Javascript:
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this note? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete-note.php", //URL to the delete php script
data : info,
success : function() {
}
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
I borrowed this code from someone else while doing research for deleting without reloading. Normally I'd see a function look something like this:
function myFunction()
Then I can call it using onclick like this:
onclick="myFunction()"
With the way this script is written, I'm not sure what "function" I'm supposed to be calling or if I need to add the name somewhere.
Any guidance or reading material would be helpful.
Thanks
You don't need to use an onclick here:
$(".delbutton") finds all the buttons with the CSS class delbutton.
.click(function() { ... }) says execute the given function when the button is clicked.
$(function() {
This means everything in there is being called when the document is ready.
As UncleDave already said, because of the .click your script should already be called onclick. It would be the same if you replace this line:
$(".delbutton").click(function() {
with this line:
function myOnClickFunction() {
and then call it onClick via onClick="myOnClickFunction()"
The click function binds the function as an event handler to the click event on all the elements matched by the selector passed to the jQuery function which is aliased to $.
(This replaces the onclick attribute)
To call the function, just click the matching element (any element that is a member of the delbutton class).
You could also trigger the event programatically with the trigger method:
$(".delbutton").trigger("click");
$(".delbutton").click(function() is listening to any click to trigger the action which is the code in your function.
You don't need onclick="" for the button tag.
How do I call this script?
You already do, it is self executing.
You do not need to register a sepperate click event to the button. The script is doing this already itself.
$(".delbutton").click(function() {
// code being executed when button is pressed
}
If you want to do it the way you are used to, just create your function in the tag like this:
<script>
function myFunction() {
// do something
}
</script>
then, your HTML element should look like this:
<button onclick="myFunction()" >
I currently have a script that I am using in my website. The goal of the script is when the user clicks the link, the javascript function will fire. This function is based off of the div id. At the end of the function I use jquery to change said div id. However, when the user clicks the link again the function still fires, even though the id has changed. What am I doing wrong? How can I get the script to only execute the first time the link is clicked?
$("#down").click(function(){
var id = $("#down").attr("class");
$.ajax({
type: "POST",
url: "vote.php",
data: "side=down&id=" + id,
success: function(){ alert("lul worked"); }
});
$('.' + id + '#down').attr('id', 'down_stay');
});
Now that you all have answered, what is the better choice, using "one" or using "unbind"?
Don't use click, use on. Or in your case, one:
$('#down').one('click', function() {
// function only fires once and then is unbound.
});
Use $("#down").one("click", function(){}); instead to make it fire only once.
Use unbind() instead.
replace
$('.' + id + '#down').attr('id', 'down_stay');
with
$( this ).unbind( 'click' );
Try using one
$("#down").one('click', function(){
The DOM events are attached to the elements and not to the attributes.
So even if you change the attributes of the element it does not mean it is a different element.
The event will only be removed if that particular element will be removed from the DOM..
My Javascript something like this
$('button').click(function(){
//load the data and place inside to #content
});
$('#id-from-data-that-load').click(function(){
//Do some action
});
So this is html tag
<button>Load</button>
<div id="content">
//Empty Data
</div>
when button LOAD clicked html will be like this
<button>Load</button>
<div id="content">
<div id="id-from-data-that-load">
content that load
</div>
</div>
BUT, when i clicked div id-from-data-load the function won't run.
How to solve it?
You need to use live for the div event instead. Here's what it should be:
$('#id-from-data-that-load').live("click", function(){
//Do some action
});
Or alternatively you could also do this:
var submitted = false;
$('button').click(function(){
// If the button was clicked before, we don't submit again.
if (submitted == true) { return false; }
// Set submitted to true, so when user clicks the button again,
// this operation will not be processed one more time.
submitted = true;
//load the data and place inside to #content
$.post("/getdata", {}, function(response) {
//after the load happened we will insert the data into the div.
$("#content").html(response);
// Do the bindings here.
$('#id-from-data-that-load').click(function(){
//Do some action
});
});
return false;
});
try:
$('#id-from-data-that-load').live("click", function() {
alert($(this).attr("id");
});
you need to bind events to elements loaded at runtime through either the .live handler or .delegate handler. That is because when you are binding events to elements they are not present on the dom. So .live and .delegate would help you achieve that. See example from #shree's answer
Bind id-from-data-that-load after data load in content.
$('button').click(function(){
//load the data and place inside to #content
$('#id-from-data-that-load').click(function(){
//Do some action
});
});
When you bind the LIs you can hardcode the function name into the onclick attribute.
<li onclick="myFunction">Blah Blah Blah</li>
I working with some ajax at the moment, the result of a successful ajax result is that some more content is add to the page on the fly. My problem is that is added on the fly it looks like I cannot attach any events to the elements that are added.
The flow of what happens is that the user selects an option from a drop-down list, the value of that selection is sent to a PHP function which then returns some more HTML to the page which is appended to a div on the page.
I know there is a problem with the elements not existing on domReady as I run a length() check and it confirms they don't 'exist' on the page.
Is there away around this so that I can run click event on the HTML that gets added after the first ajax request has returned successfully?
$(document).ready(function() {
//customise the select menus
$('#customselector').SelectCustomizer();;
$('.career_select .selectitems').click(function(){
var selectedCareer = $(this).attr('title');
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
}
});
});
$('#grade_choice_options .selectitems').click(function(){
var selectedGrade = $('#grade_choice_customselect').val();
alert(selectedGrade);
})
});
Use live() instead of click() directly:
$('.career_select .selectitems').live('click', function() { ....
live() essentially wires up any new elements that match that are added subsequently.
Try using this plugin :
http://brandonaaron.net/code/livequery/docs : Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.
I am trying to achieve this task using MooTools.
Description:
I attached an event listener to myButton link. A click on this link initiates an AJAX request and updates myDiv content based on the response text.
During this request a POST variable is being sent to "button.php", but it's not used at the moment.. (i wish to use it later)
OK, as a result, myDiv gets exactly the same link with the same ID (myButton) + a random number, so that we could see that each click generates a new number.
The problem:
After the first click on myButton, myDiv updates correctly, showing a random number. When I click myButton for the second time (this time in newly updated div), the div does not refresh anymore.
Please note that I need myButton to be inside myDiv, and myDiv must be updated (refreshed) after each click without having to refresh the entire page.
Can somebody show me how to achieve this task based on this simplified code example?
index.html
<html>
<head>
<script type="text/javascript" src="mootools-1.2.4-core-nc.js"></script>
<script>
window.addEvent('domready', function() {
$('myButton').addEvent('click', function(e) {
e.stop();
var myRequest = new Request({
method: 'post',
url: 'button.php',
data: {
action : 'test'
},
onRequest: function() {
$('myDiv').innerHTML = '<img src="images/loading.gif" />';
},
onComplete: function(response) {
$('myDiv').innerHTML = response;
}
});
myRequest.send();
$('myButton').removeEvent('click');
});
});
</script>
</head>
<body>
<div id="myDiv">
<a id="myButton" href="#">Button</a>
</div>
</body>
</html>
button.php
<a id="myButton" href="#">Button</a> clicked <?php echo rand(1,100); ?>
Look at Element.Delegation to setup the event on the myDiv container one time, so you don't have to re-attach handlers each time the contents are updated. You need to include this MooTools-More extension in your scripts as it's not part of core yet, but will be starting from version 1.3.
$("myDiv").addEvent("click:relay(a)", function() {
...
);
If you have multiple <a> links inside, and you only want to delegate a specific subset of those, add a class or some other property to distinguish them. You can use almost any selector inside relay(..). Let's say all links had a class updateTrigger added to them:
<a class="updateTrigger" id="myButton" href="#">Button</a>
the syntax would then be:
$("myDiv").addEvent("click:relay(a.updateTrigger)", function() {
...
});
See this working example where links are replaced every 5 seconds. There is only one event setup on the myDiv container and it handles all clicks to all <a>s, even the dynamic ones.
you are attaching an event to an element that you are replacing. the dom has no way of knowing that to you, the old and the new button are identical. The old button is deleted (and the event listener with it) and the new button created. So you need to re-attach the event to the new button.
That said: why does the button have to be inside the div? The mind boggles. You can always update the button text from javascript, there's no need to replace it and keep creating new listener objects.