e.preventDefault(); undefined is not a function - javascript

I'm getting the following error that is saying my e.preventDefault(); ---> "e." undefined is not a function when clicking <button class='url_qry_add' onclick='url_qry_add(this);'>. The function itself is defined before the end of my </body> and I have only invoked jQuery once.
The function structure is as follows:
var url_qry_add = function ( e ) {
e.preventDefault();
...
};
It used to be:
$( "ul.url_qry" ).on( "click", "li .url_qry_add", function ( e ) {
e.preventDefault();
...
});
But subsequent buttons added dynamically afterwards were not being picked up.
So I've been trying to figure out how to go about it and decided I should try converting the problem function to a named "invokable" function and putting the call in manually with the onclick='..' into the buttons that exist before and after dynamic creation.
Like I say, the error must be in the way I've created the function or the way I'm calling it. The error can't be to do with the order of files and I have not accidentally nested the function within another function or a document.ready.
What am I doing wrong?

<button class='url_qry_add' onclick='url_qry_add(event);'>
var url_qry_add = function (e) {
console.log(typeof e.preventDefault); // function
};
Update:
I'll try clarify how it works "internally", when we add attributes to function url_qry_add "inside" it looks like this:
document.querySelector('.url_qry_add').addEventListener('click', function (event) {
(function (event) {
url_qry_add(event, this, $(this));
}).call(event.target, event);
});
var url_qry_add = function (event, element, $jElement) {
console.log(event);
console.log(element);
console.log($jElement);
};
Hence, we have variable "event" (event object, where we have method preventDefault and so on), and "this" (current element). I hope that this explanation will help you understand where we get variable "event".

Related

I cannot make a jquery function simply due to arguments error undefined

I have the following function:
function showBox (event, element)
{
event.preventDefault();
element.hide();
alert(element.next("p").text();
}
Then here I have my event binding:
var elm = $(selector);
$(elm).on("click", function(event, elm){
showBox(event, element);
});
But it does not works and console errors that element is undefined. (referring to the function's line three)
I could use anonymous functions, but I have to use this login in several places so it seems odd to have the same code repeated everywhere. What is my probelm? thanks
You're overcomplicating it
$(selector).on("click", showBox);
function showBox (event) {
event.preventDefault();
$(this).hide();
alert( $(this).next("p").text() );
}

Simple Javascript Calling function not working/don't know how to get it to work

I'm trying to call a function and not the alert and I thought it was as easy as just doing something like this: FunctionsName(); and delete the alert(''); but it's not working for me :(
Can someone please look at the code I have below and tell me what is wrong ?
Thank you so much!!
<script type="text/javascript">
var comper;
function checkComper() {
var onResponse = function(comperNow) {
if (comper === undefined) {
comper = comperNow;
return;
}
if (comper !== comperNow) {
// show a message to the visitor
alert("New Info Added"); // <--*** I WANT TO TAKE THIS OUT AND CALL $("#append").click(function(e)
comper = comperNow;
}
};
$.get('getlastupdate.php', onResponse);
}
var tid = setInterval(checkComper, 2000);
$(function() {
var $table = $("table.tablesorter");
$("#append").click(function(e) {
e.preventDefault();
$.get('updatetable.php', function(data)
{
$table
.find('tbody')
.html('')
.append(data);
$table.trigger("update", [true]);
});
});
/*........ and so on.... */
</script>
What about changin that :
alert("New Info Added");
to that :
$('#append').trigger('click');
It will simulate a click and trigger the function.
One thing important to distinguish:
alert("New Info Added") is a function. Actually, alert() is a function, being passed the parameter "New Info Added".
$('#append').click(function(e) { is not a function, at least, not in the same way. $('#append') is a jQuery selector function, which selects all elements with an id of "append". $('#append').click() is a function that sets a click event on all elements returned in the selector.
What the whole syntax of $('#append').click(function(e) { means is on its own a syntax error. What you're doing is telling the elements found in the selector what their click function should be. But the function(e) { says that it's the start of the code of the function. That line of code isn't complete until the ending }) - the } closing the function declaration and the ) closing the call to click.
So, you can't simply replace alert("New Info Added"), which is a complete function call, with $('#append').click(function(e) {, because it's a syntax error - you haven't completed the function(e) declaration, nor the click function call. You can trigger the click function, as Karl's answer told you. Or, you can use the shortcut:
$('#append').click()
Note that this is a full proper sentence, and can therefore replace the alert.

jQuery simulate click

I want to trigger a function when the page is loaded. There are many ways to do this.
However, when I add $('#button').click in front of my function, then the getType function is not recognized. For example:
$('#button').click(function getType(id) {
//...some code
});
error: getType is not defined
What am I doing wrong?
Just to clarify, in this case I cannot use an anonymous function. Also, it does not matter to me whether I use $(document).ready or $(window).bind("load", function(), but using these I still get the “getType is not defined” error.
You either have to make your function anonymous:
$('#button').click(function() {
//...some code
});
Or pass the function itself:
function getType() {
//...some code
}
$('#button').click(getType);
If you just want to trigger a click, call .click():
$('#button').click();
Also, your id parameter won't be the element's id. It'll be the click event object. To get the element's id, you can refer to the clicked element using this:
$('#button').click(function() {
var id = this.id;
});
I suggest you read a few JavaScript and jQuery tutorials (in that order).
You are using the inline notation so, you should use an anonymous function (no name function)
your code should be:
$('#button').click(function() {
// do your stuff here
}
);
Beside that, as the titles says, you need to simulate a click event, right ? if so you better use something like:
$('#button').on('click', function() {
alert($(this).text());
});
// somewhere when you want to simulate the click you call the trigger function
$('#button').trigger('click');
see documentation here
$('#button').click(function getType(id) {
//...some code
});
Should be:
$('#button').click(function() {
[...] code here
}
);
function() { } is a callback with what code have to do when I click some element.
If you have the getType function, you can pass it as a callback:
$('#button').click(getType);
If you want to trigger a funcion, when page load, you can do this:
$('#button').trigger('click');
Or
function getType() {
[...] code here
}
getType();
Use .trigger( event [, extraParameters ] ) on the element.
extraParameters
Type: Array or PlainObject
Additional parameters to pass along to the event handler.
The added benefit is that you can pass data to the event handler, whereas if you use .click(), you cannot assign data to the object.
$("#target").trigger('click');
If you're looking to use the extraParameters:
$( "#foo" ).on( "custom", function( event, param1, param2 ) {
alert( param1 + "\n" + param2 );
});
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );
The .click() method requires a callback function. So you can do something like this instead:
//Define your function somewhere else
function getType(id) {
//...some code
}
$('#button').click(function() {
getType($(this).attr('id')); //Execute it when its clicked.
});
Try this, the id can not be passed the way you do:
$('#button').click(function() {
var id = this.id;
//...some code
});

Calling a function from an html document will not generate an alert

Hi all thanks for taking a look.
I am trying to call a javascript function when I click on the update button.
Here is the javascript
var text2Array = function() {
// takes the value from the text area and loads it to the array variable.
alert("test");
}
and the html
<button id="update" onclick="text2Array()">Update</button>
if you would like to see all the code check out this jsfiddle
http://jsfiddle.net/runningman24/wAPNU/24/
I have tried to make the function global, no luck, I can get the alert to work from the html, but for some reason it won't call the function???
You have an error in the declaration of the pswdBld function in your JavaScript.
...
var pswdBld() = function() {
---^^---
...
This is causing a syntax error and avoiding the load of your JavaScript file.
See the corrected version.
Also, you may consider binding the event and not inlining it.
<button id="update">Update</button>
var on = function(e, types, fn) {
if (e.addEventListener) {
e.addEventListener(types, fn, false);
} else {
e.attachEvent('on' + types, fn);
}
};
on(document.getElementById("update"), "click", text2Array);​
See it live.
In your fiddle, in the drop-down in the top left, change "onLoad" to "no wrap (head)"
Then change
var text2Array = function()
var pswdBld() = function()
to
function text2Array()
function pswdBld()
and it will alert as expected.
You have a syntax error in the line below..
var pswdBld() = function
^--- Remove this
supposed to be
var pswdBld = function
Also make sure you are calling this script just at the end of the body tag..
Because you are using Function Expressions and not Function Declaration
var pwsdBld = function() // Function Expression
function pwsdBld() // Function Declaration
Check Fiddle

jQuery: Call a function twice

I'm trying to run a function twice. Once when the page loads, and then again on click. Not sure what I'm doing wrong. Here is my code:
$('div').each(function truncate() {
$(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
});
$('.truncate').click(function() {
if ($(this).parent().hasClass('closed')) {
$(this).parent().removeClass('closed').addClass('open').children().show();
}
else if ($(this).parent().hasClass('open')) {
$(this).parent().removeClass('open').addClass('closed');
$('div').truncate();
$(this).show();
}
});
The problem is on line 13 where I call the truncate(); function a second time. Any idea why it's not working?
Edit jsFiddle here: http://jsfiddle.net/g6PLu/
That's a named function literal.
The name is only visible within the scope of the function.
Therefore, truncate doesn't exist outside of the handler.
Instead, create a normal function and pass it to each():
function truncate() { ...}
$('div').each(truncate);
What's the error message do you get?
You should create function and then call it as per requirement
Define the function
function truncate(){
$('div').each(function(){
});
}
Then call the function
truncate();
Another approach is to establish, then trigger, a custom event :
$('div').on('truncate', function() {
$(this).......;
}).trigger('truncate');
Then, wherever else you need the same action, trigger the event again.
To truncate all divs :
$('div').trigger('truncate');
Similarly you can truncate just one particular div :
$('div#myDiv').trigger('truncate');
The only prerequisite is that the custom event handler has been attached, so ...
$('p').trigger('truncate');
would do nothing because a truncate handler has not been established for p elements.
I know there's already an accepted answer, but I think the best solution would be a plugin http://jsfiddle.net/g6PLu/13/ It seems to be in the spirit of what the OP wants (to be able to call $('div').truncate). And makes for much cleaner code
(function($) {
$.fn.truncate = function() {
this.addClass('closed').children(":not('.truncate')").hide().slice(0,2).show();
};
$.fn.untruncate = function() {
this.removeClass('closed').children().show();
};
})(jQuery);
$('div').truncate();
$('.truncate').click(function() {
var $parent = $(this).parent();
if ($parent.hasClass('closed')) {
$parent.untruncate();
} else {
$parent.truncate();
}
});

Categories