How do I call this script? - javascript

I have a script for deleting a record without refreshing. I'm still new to javascript and trying to learn how to call out this script. Here's what I have.
My button:
<button id="<?php echo $rrr['id']; ?>" class="delbutton" onclick="">Delete</button>
My Javascript:
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this note? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete-note.php", //URL to the delete php script
data : info,
success : function() {
}
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
I borrowed this code from someone else while doing research for deleting without reloading. Normally I'd see a function look something like this:
function myFunction()
Then I can call it using onclick like this:
onclick="myFunction()"
With the way this script is written, I'm not sure what "function" I'm supposed to be calling or if I need to add the name somewhere.
Any guidance or reading material would be helpful.
Thanks

You don't need to use an onclick here:
$(".delbutton") finds all the buttons with the CSS class delbutton.
.click(function() { ... }) says execute the given function when the button is clicked.

$(function() {
This means everything in there is being called when the document is ready.
As UncleDave already said, because of the .click your script should already be called onclick. It would be the same if you replace this line:
$(".delbutton").click(function() {
with this line:
function myOnClickFunction() {
and then call it onClick via onClick="myOnClickFunction()"

The click function binds the function as an event handler to the click event on all the elements matched by the selector passed to the jQuery function which is aliased to $.
(This replaces the onclick attribute)
To call the function, just click the matching element (any element that is a member of the delbutton class).
You could also trigger the event programatically with the trigger method:
$(".delbutton").trigger("click");

$(".delbutton").click(function() is listening to any click to trigger the action which is the code in your function.
You don't need onclick="" for the button tag.

How do I call this script?
You already do, it is self executing.
You do not need to register a sepperate click event to the button. The script is doing this already itself.
$(".delbutton").click(function() {
// code being executed when button is pressed
}

If you want to do it the way you are used to, just create your function in the tag like this:
<script>
function myFunction() {
// do something
}
</script>
then, your HTML element should look like this:
<button onclick="myFunction()" >

Related

onclick needs to be double clicked

When using onclick in JavaScript to call the function nowClicked(), I need to click the object twice in order for the alert to show. Below is the code for my function.
function nowClicked() {
$('.object').click(function() {
$('.object').removeClass("clicked");
var myClass = $(this).attr("id");
alert(myClass);
$(this).addClass("clicked");
e.stopImmediatePropagation();
});
};
What is the problem?
Here's what happens the first time you click your button:
nowClicked is called because you've set it up on the button's onclick
nowClicked sets up a jQuery click handler for .object
The code inside the jQuery click handler only runs the next time you click on the button.
It looks like you are mixing up two ways of handling clicks -- one is using the onclick event, and the second is using jQuery. You need to pick one and stick to it instead of using both.
There is no need to put it inside another function,because click is itself handling a callback function.Remove the outer function nowClicked else remove the $('.object').click(function() {.In the second case you may to pass the context as a function argument.
$('.object').click(function() {
$('.object').removeClass("clicked");
var myClass = $(this).attr("id");
alert(myClass);
$(this).addClass("clicked");
e.stopImmediatePropagation();
});

How to process click event of dynamically created hyperlinks?

I have dynamically generated links like
<a name="details" id="1" href="javascript:;">Details</a>
When one of them clicked I want to process this event with javascript code like this
$(document).ready(function () {
var a = document.getElementsByName('details').item(0);
a.on('click', function () {
$.ajax({
///
});
});
});
However, even though it seems to find hyperlinks quite perfectly, on click event it doesn't enter the function.
What is wrong with the implementation?
on is a method you find on jQuery objects.
document.getElementsByName('details').item(0) returns a native DOM element.
Either use addEventListener instead of on or $("some selector") instead of getElementsByName & item.

How to associate onClick with a dynamically generated div with dojo?

I am using dojo 1.9.2, and is trying to attach an onClick function on a piece of HTML code that I created on the fly, like this:
clickableDiv = "<div data-dojo-attach-point=\"testBtn\">Click Me!</div>";
self.racks.innerHTML = clickableDiv;
and then I want to give it an onClick function after, so right below the code I putted:
connect(this.testBtn, "onclick", alert("You Clicked It!"));
For some reason not only this wont work, when I refresh the page the alert "You Clicked It!" would pop up without me clicking anything...
I Have to use this dojo version, it's part of the requirement...
Any idea or suggestion on how I can go about doing this?
Well, dojo is part of javascript, so you can probably use some javascript function, for example:
clickableDiv = "<div id=\"testBtn\">Click Me!</div>";
self.racks.innerHTML = clickableDiv;
document.getElementById('testBtn').onclick=function(){alert("You Clicked It!");};
The code mentioned in the question is correct, except for one mistake. The "onclick" event needs a handler function, not the code directly. So, enclose that alert statement by a function.
connect(this.testBtn, "onclick", function(){alert("You Clicked It!")});
Or a separate function elsewhere can be linked here a handle by passing the function or just name of the function.
function abcd() {
alert('You clicked It');
}
connect(this.testBtn, "onclick", "abcd");//same as connect(this.testBtn, "onclick", abcd);
When providing an event handler (or a callback in general), you have to provide the function as reference. When you use:
connect(this.testBtn, "onclick", alert("You Clicked It!"));
You're actually saying that you want to connect the onClick event handler to the return value of that alert(). What you actually want is like the other answers already explained by wrapping it inside a function that is passed through by reference:
connect(this.testBtn, "onclick", function() {
alert("You Clicked It!")
});
However, since you're using data-dojo-attach-point which is generally used in widgets, you could also define your event handler in a similar way, for example:
clickableDiv = "<div data-dojo-attach-point=\"testBtn\" data-dojo-attach-event=\"onClick: myClickHandler\">Click Me!</div>";
Then you can just write a function called myClickHandler in your widget that shows the alert, for example:
myClickHandler: function() {
alert("You Clicked It!");
}
He's using dojo 1.9.2. connect is deprecated and he should be using on:
on(this.testBtn, "click", function(){
alert("You Clicked It!")
});
Your data-dojo-attach-point won't get picked up in dynamically placed HTML. You would put that in a custom widget template to provide the actual reference to your node/widget. If you did have that element in a template to begin with, you could simply use the attribute on your element:
data-dojo-attach-event="onClick: someFunction"

Replacing html page text by using JQuery

I have a simple javascript code which replaces the page content....by contents of another file(test2.html)
Code:
$(document).ready(function(){
$("[href='#']").click(function() {
function getcontent(url, id) {
$("#id").load("url");
}
});
});
Now am using
<div id = "content">
<p> REPLACE </p>
</div>
click here
So now on clicking click here REPLACE should be replaced by content of test2.html...but its not happening...
I have included the required jquery.js file in my script..
No, this won't work. getcontent is a function defined in a particular scope -- that of the click handler callback function. It is not accessible in the global scope -- the scope that the onClick method receives.
You should use a genuine click handler, perhaps setting data using data attributes:
$('[href="#"]').click(function() {
$('#' + $(this).data('id')).load($(this).data('url'));
});
Using the following HTML:
click here
You have a weird setup. The function getcontent is not defined in global scope, it cannot be found by the onclick event handler in the HTML. There are other issues as well.
I suggest something like:
click here
and
$(function(){
$("a[href^='#']").click(function(){
$(this.href).load(this.rel);
});
});
$('#' + id).load(url);
In your current method above, you are passing string literals, not the variables themselves.
You seem to be misunderstanding what certain parts of your code are doing. Also, I'd recommend giving your href a real id to make things easier. You don't need to use the jQuery 'click' method and ALSO assign an onclick handler inline in the HTML.
Try this instead:
<div id = "content">
<p> REPLACE </p>
</div>
<a id="clickThis" href="#">click here</a>
$(document).ready(function() {
$('#clickThis').click(function() {
$('#content').load('test2.html');
});
});
Your code with some comments:
$(document).ready(function(){
// this will assign a click handler, you don't need an 'onclick'
// attribute on the anchor tag also
$("[href='#']").click(function() {
// but what does your click handler do?
// It defines a function that is never called.
function getcontent(url, id) {
$("#id").load("url");
}
});
});

Append an onClick event to an anchor tag using jquery?

I am trying to add an onClick event to an anchor tag ...
Previously i had ...
<a href="somlink.html" onClick="pageTracker._link(this.href); return false;">
But i am trying to avoid the inline onClick event because it interferes with another script..
So using jQuery i am trying the following code ...
<script>
$(document).ready(function() {
$('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null;
pageTracker._link(this.href);
return false;
});
});
</script>
with the html like so <a id="tracked" href="something.html">
So my question is should this be working, and if not what would be the best solution?
The correct way would be (as for jQuery)
$('#tracked').click(function() {
pageTracker._link($(this).attr('href'));
return false;
});
This will add an "onclick" event on any element with tracked id. There you can do anything you want. After the click event happens, the first line will pass href attribute of the clicked element to pageTracker.
As for your original question, it wouldnt work, it will raise undefined error. The attr works a bit different. See documentation . The way you used it, would return the value of the attribute and I think that in that case its not chainable. If you would like to keep it the way you had it, it should look like this:
$('#tracked').click(function() {
$(this).attr('onclick', 'pageTracker._link(this.href); return false;');
return false;
});
You can also try
var element1= document.getElementById("elementId");
and then
element1.setAttribute("onchange","functionNameAlreadyDefinedInYourScript()");
// here i am trying to set the onchange event of element1(a dropdown) to redirect to a function()
I spent some time on this yesterday. It turned out that I needed to include the jQuery on $(window).ready not $(document).ready.
$( window ).ready(function() {
$('#containerDiv a').click(function() {
dataLayer.push({
'event': 'trackEvent',
'gtmCategory': 'importantLinkSimilarProperties',
'gtmAction': 'Click',
'gtmLabel': $(this).attr('href')
});
});
});

Categories