Why is my app telling me my method is undefined? - javascript

I have this link:
<%= link_to_function "remove", "remove_fields(this)"%>
which outputs this html:
remove
and I have this JQuery function:
function remove_fields(link){
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}
but when I click on the link, I get this error:
Uncaught ReferenceError: remove_fields is not defined
Why is this and how do I fix it?

If you have your function declaration like this:
jQuery(function ($) {
function remove_fields ...
});
then it's only in scope inside the jQuery(function () { }) function and not visible from outside. Two methods of resolving this:
var remove_fields;
jQuery(function ($) {
remove_fields = function () { ... }
});
Declares a globally accessible variable and makes it a function as usual.
Better though:
jQuery(function ($) {
function remove_fields ...
$('a.some-class').click(remove_fields);
});
Attach the click handler programmatically from within your jQuery scope.

You should not use the onclick attribute, it's a bad practice and something that belongs back in the 90s. Instead you should add a class for your anchors and bind a handler to the click event with jQuery.
HTML
<a class="remove-fields" href="#">remove</a>
JavaScript
// This is a shorthand for document.ready
$(function(){
// Bind handler to click event
$("a.remove-fields").click(function(e){
var $this = $(this);
$this.prev("input[type=hidden]").val("1");
$this.closest(".fields").hide();
// Prevent default behavior
e.preventDefault();
});
});

May be obvious, but is the javascript linked in the head in the source of the html?

Related

call a function inside a jQuery plugin from outside on-click event

i am using following library for auto complete and mention username in my application. my question is that how can i trigger init: function from onClick of a anchor tag instead of writing in text area. any suggestion? Here is a function that i tried to write.
here is the plugin
http://podio.github.io/jquery-mentions-input/
$("a").on('click', '.tag_user_btn', function(event) {
event.preventDefault();
var txtPost = $(this).parents('.post-comment').find('textarea');
txtPost.val(txtPost.val()+" #a").focus().init();//call initilize function of library
});
If you look at the documentation (the "Methods"-part), the init() method is actually exposed on the instance of the plugin. Example:
var mention = $('textarea.mention').mentionsInput({}); // Apply the plugin
mention.init(); // call the init() method
Not sure this is the source of the problem but
$("a").on('click', '.tag_user_btn', function(event) { //WRONG
This is wrong. jQuery documentation for .on()
Correct syntax $(parentSelector).on('click', 'childSelector', function()
Instead use (for ajax event handling)
$(document).on('click', 'a.tag_user_btn', function(event) {
or for non-ajax event handling
$('a.tag_user_btn').click(function(event) which is a shorthand for
$('a.tag_user_btn').on('click', function(event))

Trigger a Jquery function that has $this. onload and onclick

Trigger a Jquery function that has $this. on window load and on click
function get_div_id(){
var f_id = $(this).attr("id");
alert(f_id);
}
$(window).load(function(){
get_div_id();
});
$('.divs_same_class_diferent_id').click(function() {
get_div_id();
});
As you can deduce, this will not work, but you have an idea of what I'm trying to do, right?
Depending on where that code is it may be running prior to the DOM being created in which case you're attempting to bind event listeners to elements that do not yet exist. try this:
function get_div_id(){
var f_id = $(this).attr("id");
alert(f_id);
}
$(document).ready(function(){
$('.divs_same_class_diferent_id').click(get_div_id);
// notice no anonymous function, this works because
// we're passing in the function object for get_div_id
});

onclick function need to execute a simple javascript function

I have a button where I am trying to add on click jquery as below
<button onclick="myFunction()">YES</button>
And
$(document).ready(function() {
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})
However, on click I am getting Uncaught ReferenceError: myFunction is not defined
What am I doing wrong and how to fix this?
Updated with a sample jsfiddle
http://jsfiddle.net/3aC7W/1/
What am I doing wrong and how to fix this?
You are defining the function inside another function, i.e. the function is not defined in global scope and hence cannot be found by the inline event handler.
Just remove $(document).ready(function() { because you don't need it there:
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
You only have to use $(document).ready(function() { ... }); if you manipulate the DOM, and also only if you place the script before the elements in the HTML document.
The better solution of course would be to bind the event handler with jQuery (and not use inline event handlers):
$(document).ready(function() {
$('button').on('click', function(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
You might have to add a class or ID to the button to make the selector more specific. Have a look at the list of available selectors.
change your code to this way to achieve click :
<button id="myFunction">YES</button>
and
$(document).ready(function() {
$('#myFunction').click(function(e){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
check it at: http://jsfiddle.net/aneesh_rr/XJ758/3/
change your code to this:
$(document).ready(function() {
window.myFunction = function(){ //you should make myFunction avaliable in global
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})

Why can't I use onClick to execute a function inside a jQuery $(document).ready function?

I'm new to JavaScript and jQuery. I want to click a button and have a js function executed. (For this example, it's just an alert, but it's actually an ajax function.)
The first alert appears, but after I click the button, I never see the second ("did it") alert. It looks like JavaScript doesn't think the doIt() function is defined when the button is clicked.
Here's the relevant code:
$(document).ready(function()
{
alert('ready');
function doIt() {
alert('did it');
};
}
)
<body>
<input name="Go" type="button" value="Go" onclick="doIt();"/>
</body>
It's because that function isn't in a global context, which is where your onclick="" is looking for it. You need to move it outside your document.ready (so it's not scoped exclusively to that closure), or (a better approach IMO) bind it inside the document.ready, here's what I mean by each:
Binding it inside (remove your onclick="" for this):
$(document).ready(function() {
alert('ready');
$("input[name='Go']").click(doIt);
function doIt() {
alert('did it');
}
});
or the anonymous version (again remove your onclick=""):
$(document).ready(function() {
alert('ready');
$("input[name='Go']").click(function() {
alert('did it');
});
});
Or move it outside (keep your onclick=""):
$(document).ready(function() {
alert('ready');
});
function doIt() {
alert('did it');
}
You define doIt in your document.ready as a function statement.
Either you should use a function expression
or declare the function out of the ready function.
$(document).ready(function()
{
alert('ready');
doIt = function() { //now has global scope.
alert('did it');
};
}
)
<body>
<input name="Go" type="button" value="Go" onclick="doIt();"/>
</body>
(yes, the onClick is not really the jQuery way of doing it and probably should be replaced by a click handler defined in the ready function, but it works and is allowed.
What you need to do is bind a "click" event to it using jquery like this.
jQuery(document).ready(function($) {
$('#my_button').click(function() {
alert('i was clicked');
});
});
<input type="button" id="my_button" value="Go" />
Here is a live jsfiddle demo for you: http://jsfiddle.net/8A5PR/
Here is the manual page for you: http://api.jquery.com/click/
Javascript has two kinds of scope, global, and function level. If you declare doIt inside a function, it will not be visible outside the function. There are a few ways to fix it
//just declare the function outside the ready function
$(function() {
});
function doIt() { alert('did it'); }
//decare a variable outside the function
var doIt;
$(function() {
doIt = function() { alert('did it'); }
});
// if you dont use var, variables are global
$(function() {
doIt = function() { alert('did it'); }
})
$(document).ready(function()
{
});
is an event handler for document.ready, the functions inside that handler are within that scope.
A better method is to insert a handler for your click event inside, then call that function there.
$(document).ready(function()
{
alert('ready');
$('body input').click(function(){
doIt();
});
function doIt() {
alert('did it');
};
});
This ALSO has the side effect of removing code from your markup (a good thing) in that you can remove that onclick from your input tag.
What you are doing right now is simply putting a function doIt() inside a (for all intents and purposes) window.onload event. This function will never get called outside of the document.ready unless you bind it to an element because it's stuck inside the scope of document.ready.
You need to move your function outside of the document.ready so it can be called by outside events.
Just a little link for reference: http://www.webdevelopersnotes.com/tutorials/javascript/global_local_variables_scope_javascript.php3
Try this...
$(document).ready(function() {
alert('ready');
$("#Go").submit(function(event) {
alert('did it');
});
});
<input name="Go" id="Go" type="button" value="Go" />
Yes, as mentioned by others you really need to move the function outside of the jquery ready declaration. Also please note that javascript is case sensitive, hence you should use onClick rather than onclick. Regards

Changing the onclick event delegate of an HTML button?

How do you change the JavaScript that will execute when a form button is clicked?
I've tried changing its onClicked and its onclicked child attributes like so:
$('mybutton').onClick = 'doSomething';
and
$('mybutton').attributes["onclick"] = 'doSomething()';
Neither seem to work. My other options are:
To have two buttons and hide one and show the other.
To have it directed to a function that evals a string and change the string to the function I want to execute.
Neither seem very elegant.
I'm using Prototype as a js library so it that has any useful tools I can use them.
If the original onclick event was set through HTML attributes, you can use the following to overwrite it:
$("#myButtonId").setAttribute("onclick", "myFunction();");
For Prototype, I believe that it would be something like this:
$("mybutton").observe('click', function() {
// do something here
});
EDIT: Or, as it says in the documentation, you could simply specify the function you want to call on click:
$('mybutton').observe('click', respondToClick);
function respondToClick(event) {
// do something here
}
But this is all, again, Prototype-specific.
Using the Prototype framework you can do:
Event.observe("mybutton", "click", clickHandler);
or:
Event.observe("mybutton", "click", function() {
alert("Button clicked!");
});
or:
$("mybutton").observe("click", clickHandler);
or:
$("mybutton").observe("click", function() {
alert("Button clicked!");
});
See the Event class documentation
The general way to set an onclick handler in javascript is to set onclick to a function, by passing it the name of a function directly, not in a string. So if myButton is set to a DOM Element, you would write:
myButton.onclick = doSomething;
So when you click the 'mybutton' button, the doSomething function will be called as doSomething(). For anonymous functions, you can write:
myButton.onclick = function() {
alert("myButton was clicked!");
};
In JQuery it's
$("#myButtonId").click(myFunction);
function myFunction(){
alert("Clicked");
}
Or if you want to put the function inline:
$("#myButtonId").click(function(){
alert("Clicked");
});
If you are using JQuery firstly make sure you use the relevant selector prefix (IE: If your using the Id of the element put a # in front of it). Secondly it's the click method to assign a callback to the click event.
Last I used Prototype, it was something like this:
Event.observe('mybutton', 'click', doSomething);
By the way, your examples might've even worked if you didn't quote the function names.
EDIT: Yes, Element.observe(element, eventName, handler) and someElement.observe(eventName, handler) also work. And don't quote the handler name - you want to pass the function not a string!
I found a solution for your issue with prototype under firefox:
$("#myButtonId").writeAttribute('onclick', ''); // first remove the attribute
$("#myButtonId").observe('click', function () { ... }); // then add the event

Categories