onclick function need to execute a simple javascript function - javascript

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");
}
})

Related

JavaScript Pop up : Invoking in JQuery

In my application I am using a simple JavaScript popup and successfully invoking it this way-
<a href="javascript:popup('Hello World')>Click Me</a>
I was wondering whether it is possible to invoke the same popup on other jQuery events. For instance
$("#some_button_id").click( function() {
javascript:popup('Hello World');
});
The above method doesn't work. Any other solution?
EDIT - You don't need the javascript: part because you are not attaching javascript inline.
But that is not the cause of the error so make sure that you wait until the DOM is ready before attaching an event handler.
$(function(){
var popup = function(msg){
alert(msg);
}
$("#some_button_id").click( function() {
popup('Hello World');
});
});
and of course make sure you define popup() somewhere
If the popup function is defined on your page then you should use
$("#some_button_id").click( function() {
popup('Hello World');
});
The javascript: prefix is only needed when you use javascript code directly inside your html attributes.
$("#some_button_id").click( function() {
popup('Hello World');
});
should work.
EDIT
this will work for sure if the id exit when the event if fired , wether or not it has been created when the the listener was added , it is called delegation :
$(document.body).click( function(e) {
if(e.target.getAttribute("id")=="some_button_id"){
popup('Hello World');
}
});

Toggle text with function called with onclick

my question is a short one but I couldn't figure it out by myself. I've got a function like -> http://jsfiddle.net/gtU56/ . I'm calling a javascript-function with an event-listener(onclick) in my html-code. The function itself is more complex but I need the last snippet. By clicking 'Show More' the text should change. Why won't the text change?
Because the toggleText function isn't available when the html code is rendered.
In other words the function isn't set until the page is ready so the onclick function doesn't reference anything.
Either have the function like here http://jsfiddle.net/gtU56/2/
or have it in the head of the page because its needs to be ready immediately
If you want it to wait for the ready state you can do the following and remove the onclick action all together
http://jsfiddle.net/gtU56/7/
$(".text").click(function()
{
$(".text").toggle();
});
toggleText = function () {
$('.text').toggle();
}
check here http://jsfiddle.net/gtU56/3/
It's because of how you're loading the function. Switch it from onLoad to no wrap (head) and it works fine.
jsFiddle example
Using jsFiddle's onLoad wraps your function in a window.onload call like this:
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
function toggleText() {
$('.text').toggle();
}
});//]]>
</script>
While no wrap (head) just adds it normally like this:
<script type="text/javascript">
//<![CDATA[
function toggleText() {
$('.text').toggle();
}
//]]>
</script>
since you are already claiming having jquery, you need not use inline javascript. try this
var elems = $('.text');
elems.click(function(){
elems.toggle();
});
fiddle : http://jsfiddle.net/gtU56/5/
$('.text').click(function() {
$('.text').toggle('slow', function() {
// do your animation..
});
});
​
Js Fiddle
This is the solution - http://jsfiddle.net/gtU56/6/
You need to first make sure that the function is registered after page load. Then, bind a click event to the div.
Hope this helps!
First you should organize you jQuery code like this:
$.(document).ready(function() {
// enter jQuery code here
});
Otherwise you're accessing a not completly loaded html document.
Also, you don't need the event-listener if you are using jQuery.
This should work for you:
$.(document).ready(function() {
$('.text').click(function() {
$(this).toggle();
});
});
Is very easy. You can use ID or CLASS.
onclick="$('NAME ID or CLASS').toggle(ANIMATION or DURATION);"
<div>
<div class="text" onclick="$('.text2').toggle(400);">Show More</div>
<div class="text2" style="display:none">Show Less</div>
</div>

get the value of rel attribut of a link on click event of link using jquery

I have many link like this with different rel attributes
buy
I want to get the value of rel attribute on click... but this code doesn't seem to work but
firebug also doesn't fire any error in console. What am i doing wrong?
$("a.buy").click(function(event) {
event.preventDefault();
var msg = $(this).attr('rel');
alert(msg);
});
update: I corrected the html error i had. Its not preventing default. And the click event doesnt seem to work.
Adding the code top of all the other scripts worked.
It is working fine here http://jsfiddle.net/niklasvh/NFfe5/ but note that you have an error in your HTML, you are missing the quotation mark around href=#"
Make sure your code is wrapped in a DOM ready as well:
$(function(){
// your code
});
try this
$(document).ready(function(){
$("a.buy").live('click',function(event) {
event.preventDefault();
var msg = $(this).attr('rel');
alert(msg);
});
});
this is bound to the global object in this case. I believe that event.target will be the DOM object you want.
$("a.buy").click(function(event) {
event.preventDefault();
//here, this refers to the global object, not the a element
//unless jquery is doing some magic to bind it
//event.target at this point in execution should be the a element
var msg = $(this).attr('rel');
alert(msg);
});
I have tested, the write is no problem. Code is as follows:
buy
<script type="text/javascript">
$(function () {
$(".buy").bind("click", function () {
alert($(this).attr("rel"));
});
})
</script>

Why is my app telling me my method is undefined?

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?

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