11 Replies - 7052 Views - Last Post: 11 August 2013 - 09:18 AM

#1 ghqwerty  Icon User is offline

  • if($spareTime > 0){ $this->writeCode(); }
  • member icon

Reputation: 43
  • View blog
  • Posts: 903
  • Joined: 08-August 08

Event not triggering function

Posted 11 August 2013 - 05:26 AM

Sorry for the long post, but i feel a lot of explaining is necessary.

So as a work in progress i am trying to create a 'profile updater' through ajax such that the user can stay on the same page.

I have succesfully created the function to change the displayed data into form inputs and visa versa when an 'edit' button is clicked.

The bit that i am now stuck on is submitting the data through ajax (p.s.i'm only at the start)

Here is the code:
function formatAndCheck(userID, formElems){
	var form = document.forms["profileUpdate"+userID];
	
	//retrieve all elements from page
	for ( var ii = 0; ii < form.elements.length; ii++){
		formElems[ii] = form.elements[elements[ii]+"Form"+userID].value;	
	}
	
	//note the date is in format d/m/yyyy (split using / )
	var temp = form[3].split("/");
	for (var ii = 0; ii<3; ii++){
		formElems[ii+3] = temp[ii];
	}	
	
	//TODO: add security checking
	
	
	//alert("Form: "+form+" \nuserID: "+userID);
}

$(document).ready(
	function(){		
		
		//toggle form mode
		$("#editFormButton").click(
			function(){				
				//get the userID of the form				
				var ID = $("#editForm input[name=ID]").val();
				changeToForm(ID);				
			}
		);
		
		//check data and submit the form to ajax handler
		$("#submitUpdate").click(
			function(){
				var formElems = new Array();
				alert("test1");
				formatAndCheck(ID, formElems);
				//perform ajax call
				alert("test");
				alert(testArray(formElems));
				// var request = $.ajax(
					// {
						// type: "POST",
						// url: "ajaxhandler.php",
						// data: { formElementsArray : formElems},
						// succes: function(){
									// alert("Success");
								// }
					// }
				// );
				
			}
		);
		
		
	}
);



The format and check function is designed to read the data from the form, check it is all valid and secure and then return each element in an array.
(off the main topic, i want the formElems in this to act as a reference, but when i tried &formElems in the arguments of the function everything broke - subsequently found out that js doesn't work this way and so i was in the process of checking how js references objects, hence the testarray function. The testArray function loops all elements in an array and puts them into an output line by line which is then returned.)

Here is the problem:
$("#submitUpdate").click(...
doesn't seem to be firing. Even when the function was commented down to simply alert("test"); - nothing.

I have 2 theories for why:
1. the submitUpdate button is only generated by the above function changeToForm and hence isn't available on page load. Could this be the issue?
2. something in the first click event (generating the form) is still 'running' and hence the page isn't 'ready' and won't process the next click event. Despite the 'changeToForm' function being completed (at least visually) maybe i need to do something to signal to the page that it is complete?

Please help a JQuery noob out :)/>

Is This A Good Question/Topic? 0
  • +

Replies To: Event not triggering function

#2 andrewsw  Icon User is offline

  • say what now
  • member icon

Reputation: 6409
  • View blog
  • Posts: 25,904
  • Joined: 12-December 12

Re: Event not triggering function

Posted 11 August 2013 - 06:01 AM

I assume that you've correctly attached the jQuery library, but this

$(document).ready(
	function(){

is incorrect. You are inserting your code in an anonymous function that is never called, as far as I can tell from your code. IGNORE THIS! (my mistake)

BTW A brief look also tells me that you are over-writing elements of formElems in your second loop.

You need to learn to use your browser's console; in particular, to check for error messages. There are links in my signature.

This post has been edited by andrewsw: 11 August 2013 - 08:18 AM

Was This Post Helpful? 0
  • +
  • -

#3 ghqwerty  Icon User is offline

  • if($spareTime > 0){ $this->writeCode(); }
  • member icon

Reputation: 43
  • View blog
  • Posts: 903
  • Joined: 08-August 08

Re: Event not triggering function

Posted 11 August 2013 - 07:01 AM

I may be new to jQuery, but surely that is correct as it's a handler for waiting until the page loads. It is called when the document is ready.

Quote

http://www.w3schools...uery_syntax.asp
$(document).ready(function(){

   // jQuery methods go here...

}); 


also, the first function called by the 'editFormButton' click event works fine. (Btw thanks for spotting the overwrite issue)

I also do use firebug and in this case what happens is aftert the changeToForm function is completed, it delves into the jquery core code(which i have literally no idea what is happening inside) ending at this point:

Quote

if ( !(eventHandle = elemData.handle) ) {
			eventHandle = elemData.handle = function( e ) {
				// Discard the second event of a jQuery.event.trigger() and
				// when an event is called after a page has unloaded
				return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
					jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
					undefined;
			};
			// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
			eventHandle.elem = elem;
		}


and then stops. So i don't know what is wrong :/
Was This Post Helpful? 0
  • +
  • -

#4 andrewsw  Icon User is offline

  • say what now
  • member icon

Reputation: 6409
  • View blog
  • Posts: 25,904
  • Joined: 12-December 12

Re: Event not triggering function

Posted 11 August 2013 - 08:17 AM

Yes, you are right about the ready-code. It was early in the morning for me, sorry!

I was confusing it with:

$(function() {
     // Handler for .ready() called.
    });

Still, I would rather rely on the docs than w3schools.

If there is no error in the console then I don't know why it is taking you into the jQuery library, and pausing. Unless, that is, you have managed to create a breakpoint in the code(?).

Don't play with the jQuery-library code! If you start to do this then it's time to walk the dog, or go to the pub :helpsmilie:

Throw in lots of console.log(somevariable); statements in your code, so that you can see what is happening to your variables or arrays.

If you are stepping through your code in the console then use Step Over, rather than Step or Step Into, at various points so that it doesn't go into the jQuery library-methods. If you do happen to trip into the jQuery library click Step Out and it will execute the remaining library code (or method) and should head back to your own code.

This post has been edited by andrewsw: 11 August 2013 - 08:21 AM

Was This Post Helpful? 0
  • +
  • -

#5 andrewsw  Icon User is offline

  • say what now
  • member icon

Reputation: 6409
  • View blog
  • Posts: 25,904
  • Joined: 12-December 12

Re: Event not triggering function

Posted 11 August 2013 - 08:31 AM

Also, you haven't posted your changeToForm function so it will not be easy for anyone to help you with this :whistling:

Off-topic
 // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events

the jQuery library would be even more compact if it didn't have to account for IE's weirdness :whistling:

This post has been edited by andrewsw: 11 August 2013 - 08:33 AM

Was This Post Helpful? 0
  • +
  • -

#6 ghqwerty  Icon User is offline

  • if($spareTime > 0){ $this->writeCode(); }
  • member icon

Reputation: 43
  • View blog
  • Posts: 903
  • Joined: 08-August 08

Re: Event not triggering function

Posted 11 August 2013 - 08:45 AM

Haha, not a problem! And i was only using W3Schools since that's where I originally read about it.

Trust me, I am not fiddling with the library code one bit! that just happened to be where my magical mystery tour took me when stepping over code :P/>/>

As for the console though, there appears to be no errors (apart from a couple of css warnings which shouldn't matter at all)

Problem:
So seeing as there appears to be nothing 'faulty' about what i have written i decided to try and check whether it was in fact my first theory. I changed the "#submitUpdate" identifier for a simple "p" and both functions worked fine. So the issue lies somewhere in the fact that the submitUpdate button is generated by the javascript AFTER the page has loaded.

Since i already have a div in place from page load called "submitAnchor" i can use this id as a reference/workaround for the time being. But it would be nice to know of a more direct solution if there is one?


Edit:
Although the issue isn't in here, here's my changeToForm function. It is less than elegant to say the least and i'm sure there is probably a jQuery functon to do this more concisely but oh well, it works:
function changeToForm(ID){	
	//set a list of elements	
	//check whether the target is already in form format when edit clicked
		//yes -> revert to display mode
		//no -> change to form mode	
	if (!document.getElementById(elements[0]+"Form"+ID)){
		//switch to form mode
		//alert("Display mode");
		for (var ii = 0; ii < elements.length; ii++){
			//if there's data for a row, store it for later
			if(document.getElementById("formElem"+elements[ii]+ID)){
				prevContent[ii] = document.getElementById("formElem"+elements[ii]+ID).textContent;
				document.getElementById("formElem"+elements[ii]+ID).innerHTML = '<input id="'+elements[ii]+'Form'+ID+'" type="text" value="'+prevContent[ii]+'" class="slimline" />';
			} else {
				//if not, store nothing as a place holder
				prevContent[ii] = "";
			}			
		}		
		//append the submit button to the end
		document.getElementById("submitAnchor"+ID).innerHTML += '<input id="submitUpdate" type="button" value="Update Details" class="float-right"/>';
	} else {	
		//already in form mode, switch back to display mode
		//alert("Form Mode");
		for (var ii = 0; ii < elements.length; ii++){			
			if(document.getElementById("formElem"+elements[ii]+ID)){
				document.getElementById("formElem"+elements[ii]+ID).innerHTML = prevContent[ii];
			}			
		}		
		remove("submitUpdate");		
	}
	
	return true;
}



Edit 2:
I am more than positive that the entirety of the internet would be a lot more concise if we didn't have to account for IE's 'weirdness'. At least up untill IE8/9 when they started to get their act together

This post has been edited by ghqwerty: 11 August 2013 - 08:49 AM

Was This Post Helpful? 1
  • +
  • -

#7 andrewsw  Icon User is offline

  • say what now
  • member icon

Reputation: 6409
  • View blog
  • Posts: 25,904
  • Joined: 12-December 12

Re: Event not triggering function

Posted 11 August 2013 - 08:51 AM

If I've understood, then you can use jQuery on() to attach events to elements that aren't already in the DOM.

You have already loaded the jQuery library so you shouldn't be reverting to (vanilla) JS and document.getElementById, use $('#someid'). (Kinda the whole point of loading the library :bigsmile: )

Mixing and matching JS and jQuery is useful, and necessary, sometimes. But if there is a jQuery method available then you should use it in preference.

This post has been edited by andrewsw: 11 August 2013 - 08:54 AM

Was This Post Helpful? 0
  • +
  • -

#8 andrewsw  Icon User is offline

  • say what now
  • member icon

Reputation: 6409
  • View blog
  • Posts: 25,904
  • Joined: 12-December 12

Re: Event not triggering function

Posted 11 August 2013 - 08:57 AM

Quote

At least up untill IE8/9 when they started to get their act together

There is still a lot of unpleasantness in IE8 (fractures is a nice word). Maybe at IE20 they will get it right :)

fracture:

Quote

To abuse or misuse flagrantly, as by violating rules

This post has been edited by andrewsw: 11 August 2013 - 08:59 AM

Was This Post Helpful? 0
  • +
  • -

#9 ghqwerty  Icon User is offline

  • if($spareTime > 0){ $this->writeCode(); }
  • member icon

Reputation: 43
  • View blog
  • Posts: 903
  • Joined: 08-August 08

Re: Event not triggering function

Posted 11 August 2013 - 09:01 AM

OK, so i only briefly skimmed that, but i ammended the code as follows:

$("#submitUpdate").on("click",
			function(){



and still no luck.

Also, i have only just started using jQuery so i haven't converted anything yet. I am still unsure as to how exactly it all meshes together. I originally thought it could all just be used interchangeably, but then stuff like ".value" having to be ".val()" led me to hesitations about mixing the 2 formats in the same function.
Was This Post Helpful? 0
  • +
  • -

#10 andrewsw  Icon User is offline

  • say what now
  • member icon

Reputation: 6409
  • View blog
  • Posts: 25,904
  • Joined: 12-December 12

Re: Event not triggering function

Posted 11 August 2013 - 09:13 AM

For an element that isn't in the DOM I think it requires event delegation:

$("#editForm").on("click", "#submitUpdate", 
    function () {


assuming the submit button is within the form editForm, which already exists on the page.

If not then you'll have to switch "briefly skimming" to "reading" and "studying" (something more than 4 minutes).

This post has been edited by andrewsw: 11 August 2013 - 09:16 AM

Was This Post Helpful? 1
  • +
  • -

#11 ghqwerty  Icon User is offline

  • if($spareTime > 0){ $this->writeCode(); }
  • member icon

Reputation: 43
  • View blog
  • Posts: 903
  • Joined: 08-August 08

Re: Event not triggering function

Posted 11 August 2013 - 09:17 AM

Bingo! I actually tried that myself with no luck, but had omitted the # identifier... It works now, FINALLY!

Thank you
Was This Post Helpful? 0
  • +
  • -

#12 andrewsw  Icon User is offline

  • say what now
  • member icon

Reputation: 6409
  • View blog
  • Posts: 25,904
  • Joined: 12-December 12

Re: Event not triggering function

Posted 11 August 2013 - 09:18 AM

Quote

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.


View Postghqwerty, on 11 August 2013 - 04:17 PM, said:

Bingo! I actually tried that myself with no luck, but had omitted the # identifier... It works now, FINALLY!

Thank you

You are welcome.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1