This is probably something simple but it's driving me nuts.
I'm making some pagination using jquery and a while loop which has a variable called "pageNum" that updates at the end of the loop and represents the page being written out. Obviously pageNum is added to at the end of each iteration. Fine.
Here's the code that's giving me a hard time:
$('#page' + pageNum).click(function(){
alert(pageNum);
});
So that id works properly and will assign a click even to (for example) a span with an id of page3 if 3 is the current pageNum. The problem is, when I click on that span, the pageNum that is alerted is always the last value of pageNum that was set in the loop. So if there's 8 pages, it will always alert 8. So, I figured it must be always pulling in the current value, so I tried passing pageNum in like this:
$('#page' + pageNum).click(function(pageNum){
alert(pageNum);
});
But now the alert shows [Object object].
I've tried creating variables inside and out of the click event and assigning them the value of pageNum and nothing seems to work.
This must be something really stupid, can someone please help me out? I need to have the current pageNum usable within that click event.
Thanks in advance for your help!.
Instead of referencing the pageNum variable directly, just get it dynamically from each link, for example:
$('#page' + pageNum).click(function(){
alert(this.id.replace('page',''));
});
Or give them a class, say .pageLink and bind them all at once, like this:
$('.pageLink').click(function(){
alert(this.id.replace('page',''));
});
Currently you're referencing a single pageNum variable from your loop which changes and ends up whatever it was at the end of the loop. You either need to pass it in a closure or ignore it altogether, like above, or use event data passed to .bind(), like this:
$('#page' + pageNum).bind({id: pageNum}, 'click', function(e) {
alert(e.data.id);
});
The third option actually works great, Nick just had the parameters mixed around - I recently needed to use bind in this fashion for a plugin im creating and it works awesome! See below for fix:
$('#page' + pageNum).bind('click', {id: pageNum}, function(e) {
alert(e.data.id);
});
jQuery documentation cleared it up for me; http://api.jquery.com/bind/
.bind( eventType, [ eventData ], handler(eventObject) )
$('#page' + pageNum).click(function()
{
var pageNum = $( this ).attr( 'id' ).match(/page([0-9]*)/)[1];
alert( pageNum );
});
Related
JQuery does not recognize cloned objects, I have a Jquery code which clones a div and changes the name of the inputs inside it, the thing is that I need to perform certain functions with those cloned inputs and I am checking that jQuery does not recognize them, like If they did not exist, I leave you here the code, thanks in advance.
Jquery code cloning and ID renaming (work perfect code)
$('#div-materiales-{{$num}}').clone().appendTo('#material-form').prop('id', 'div-materiales-' + i);
$('#div-materiales-' + i).find('input.total').attr('id', "total-" + i);
$('#div-materiales-' + i).find('input.total').attr('name', "total-" + i);
i++;
Code that should show an alert when clicking the total input-1
$(document).ready(function () {
$("#total-1").click(function() {
alert('funciona');
});
});
PS: I understand that it is the cloning that gives me problems because the initial total is total-0 and the code above but with total-0 the alert jumps but as I have commented here the total-1 (which would be the cloning) does not I get the alert to jump.
Use "on" for dynamic bindings
$("body").on('click','#total-1',function(){ // Previously i had issue here for dynamic bindings
console.log('clicked')
});
$("body").on('keyup','#total-1',function(){
console.log('key up')
});
You need to use on, and attach the event to an element that always exists:
$('body').on('click', '#total-1', function() {
sorry but couldn't find a solution for my problem so far.
I am writing a kind of an email template editor as a little task for my boss.
$('a, span').click(function(event){
var editableElement = $(this);
if($(this).is('a')){
event.preventDefault();
}
if(editableElement.is('span')){
processType(editableElement, 'simpleText', modalContent)
When I send the 'editableElement' variable first time, everything's fine, sends object to my function, where I open up a modal window, where there is a textarea, which if i enter text and submit it using only jQuery it will put the text from the textarea (using .val()) to my desired element, in this case a "span" element which is the 'editableElement' using .text() on it. No problem, it works for the first time. After I try to edit a second span, it constantly modifies the previous span too, with whatever I enter in to the textarea (which is cleared out completely, the problem is NOT here) I've ran a fast debug with a simple foreach on the editable element, and the problem is that for some reason it keeps adding objects to the editableElement variable everytime I send it to the function. The number of spans I try to edit, the number of objects will be in my variable all with the index of 0.
Any idea what could be the cause of this?
Thanks in advance!
EDIT:
As requested the whole code in one piece which I have problem with, though it was the whole code before too, I'm in an early stage of writing it, I understand that it was hard to read though, perhaps now it is properly formatted as requested.
$(window).load(function()
{
var modalContent = $('#modalContent');
modalOverlay = $('#modalOverlay');
$('a, span').click(function(event)
{
var editableElement = $(this);
if($(this).is('a'))
{
event.preventDefault();
}
if(editableElement.is('span'))
{
processType(editableElement, 'simpleText', modalContent)
}
});
$('#codeGenButton').click(function()
{
var container = $('#codeContainer');
container.empty();
container.text(getPageHTML());
});
$('#modalClose').click(function()
{
$(this).parent().parent().animate({'opacity': '0'}, 200,
function(){
$(this).css({'display': 'none'});
});
});
});
function fillData(targetDomElement, modalObject)
{
$('#modalSubmit').click(function(){
targetDomElement.text($('#simpleTextEdit').val());
closeModalWindow();
});
}
function processType(targetDomElement, type, modalObject)
{
modalObject.empty();
if(type == 'simpleText')
{
modalObject.append("<p id='simpleTextEditTitle'>Text editor</p><textarea id='simpleTextEdit'></textarea>");
getModalWindow();
fillData(targetDomElement, modalObject);
}
}
Step by step of what it should do:
First of all, the html should not be needed for this, it does not matter, and this is the whole code honestly.
When you click on either an element of (span) or an element of (a) it triggers the function.
It will check if it was actually a (span), or an (a) element.
Currently if it is an element (a), it does nothing, not implemented yet, but if it is a (span), it will call in the processType function, which it sends the "handler?" of the element to namely "editableElement" which has been declared right after the click event, the 'simpleText' which gets send too, is just to differentiate between element types I will send to the processType function later on, and for the last, "modalConotent" is only a div container, nothing more.
Once the function gets the data first, it will make sure, that the modal window gets cleared of ALL data that is inside of it, then it will append a bit of html code as you can see, in to the modal window, which pops up right after I have appended data in to it, it is literally just a 'display: block' and 'animate: opacity: 1' nothing special there.
Lastly it will trigger the 'fillData' function, which will put my desired data from '#simpleTextField' which is only a (textarea) where you can write in, to my desired element 'editableElement' which is the element you have clicked at the first place, a (span) element after the submit, which is again, just a css of 'display: none' and 'opacity: 0' closes the modal window.
THE END.
Your problem is here
function fillData(targetDomElement, modalObject)
{
$('#modalSubmit').click(function(){
targetDomElement.text($('#simpleTextEdit').val());
closeModalWindow();
});
}
Each time this function is called it adds a new click handler with the perameters at the time the handler was created. This handler is added in addition to the already created handlers. See a demo here. After successive clicks on the spans notices how fillData is called multiple times for a single click.
To give you the best possible answer I need to know where your modalSubmit button is in relation to modalContent. Also is is modalSubmit dynamic or static on the page?
Here is a fairly hacky fix in the mean time using on and off to bind and remove the handler respectively:
function fillData(targetDomElement, modalObject)
{
$('#modalSubmit').off("click"); /*Clear Hanlders*/
$('#modalSubmit').on("click", function(){
console.log("fill data");
console.log(targetDomElement);
targetDomElement.text($('#simpleTextEdit').val());
/*closeModalWindow(); Don't have anything for this so ignoring it*/
});
}
Demo
I've solved it myself by using .submit() (of course this means adding form, and an input with the type of submit) instead of .click() when I send the request to modify the element I've clicked on originally.
I don't understand though, why it did what it did when I've used the .click() trigger.
I have a delete modal set up, and the id of the module I want to be deleted is passed and set to the 'delete' button on the modal. The code below does this for me:
$(document).on("click", "#deleteModule", function () {
var id = $(this).data('id');
$("#deleteModuleButton").attr('data-id', id);
});
What this does is lets me click an 'X' by the module, and after I click that a modal drops down asking me if I'm sure. By clicking the X I pass the id to the modal, so that upon clicking 'I'm sure' it deletes the correct module by id.
Unfortunately it seems that the same id is passed every time I click the function. If I have ids 74, 75, and 76 on a page, I can delete the first one I click, say '74' - then every time I click 'X' on the other modules (75, 76), the initial value that was set from the first deletion (74) is never overwritten by the next element, so the other modules can't be deleted unless I refresh the page and try it again.
Is there something inherent on the onclick function that I'm overlooking, and is there a way to correct this?
If I am understanding your problem correctly, you can try to do something like:
$(document).on("click", "#deleteModule", function () {
var id = this.data('id');
showConfirmClosePrompt(id); // Re-factor to use across all modals
});
That way, you'll have the id no matter what modal id you click the X on. You may want to check to see if var id = $(this).data('id'); is your real problem too.
The answer to this was in the statement:
var id = $(this).data('id');
The better was to do this is:
var id = $(this).attr('data-id', id);
The former binds the same value, whereas the latter does not and can be reused. Changing this line in every repeated instance solved all of my problems!
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..
http://jsfiddle.net/piezack/X8D4M/5/
I need the change created by clicking the button to be detected. At the moment you have to click inside the field and then outside for it to detect any change.
Thanks guys.
The code for the button CANNOT be altered. Good tries so far though.
Was overcomplicating things. Answer http://jsfiddle.net/piezack/X8D4M/56/
Example using trigger:
//waits till the document is ready
$(document).ready(function() {
$('button.butter').click(function() {
var $form6 = $('#FormCustomObject6Name');
$form6.val('Text has changed');
$form6.trigger('change')
});
$('#FormCustomObject6Name').change(function() {
var x = $('#FormCustomObject6Id').val();
$("a").filter(function() {
return this.href = 'http://www.msn.com'
}).attr('href', 'http://www.google.com/search?q=' + x);
alert(x);
});
});
i think that jmar has the right idea...if i understand correctly you want to be able to type whatever in the box and without clicking out of it to have the button change it to the text has changed.
i dont know if that alert is really necessary, but you can do this if the alert is not needed:
http://jsfiddle.net/X8D4M/24/
To trigger the change event simply add a .trigger after setting the value.
Also, you're selector for the link wasn't working so I just changed it to #link.
http://jsfiddle.net/X8D4M/22/