A click function not working - javascript

my a click jquery function is not working, it just doesn't give any errors at console at all too.
Here is the link -
Edit
and here is the click function
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
It doesn't popout the alert box, nor it does show me error in console.
Okay, someone asked for more info -
The link is added with jquery, by pressing button, and as id it takes one of the input fields value and inserts it as link with id from input field. There are no duplicate ids, all javascript scripts are located at the end of head tag, and the a click function is located last in part.

Based on your edit that the <a> tag is being inserted dynamically, you'll need to use jQuery's .on() (jQuery version 1.7 and later) or .live() method to attach the click handler.

This code should work, so I suppose there is some other error before this code runs that prevents correct Javascript execution.
Edit: OR the DOM is not yet ready when you insert the Javascript code. Then you should use
$(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});​
});

Are you wrapping it on the ready event or after the element has been displayed? If so then it should work;
http://jsfiddle.net/sWeRf/

Either place this code after the Edit on the page, or put it in the head with $(document).ready(function() { //Place code here. });

Can you try replacing your JS code with the following (put between the HEAD tags)
<script type="text/javascript">
$(document).ready(function(){
$('a#lang').click(function(){
alert($(this).attr('id'));
});
});
</script>

Are you checking the document is loaded before applying your JQuery click handler?
e.g.
$(document).ready(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
});

Instead of using document.ready you can use an anonymous function that does the same thing.
Like this:
$(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
});

To remove the item do this:
$('#language_c').remove();

Related

Click event of 'a' tag in jquery

I need to trigger click events of "a" tags which are in "deletable" class. I saw some similar question in SO, but following code doesn't work for me. What i'm trying to do is to delete relevant <li> from <ul>.
$(document).ready(function () {
$('.deletable').live("click", function () {
alert("test"); // Debug
// Code to remove this <li> from <ul>
});
});
<form ...>
<ul>
<li>OneDelete</li>
<li>TwoDelete</li>
<li>ThreeDelete</li>
</ul>
</form>
I assume i'm using incorrect object hierarchy inside $('...') tag. But i don't have enough js/jquery/DOM knowladge to solve this problem. please help.
EDIT
Thanks for the answers, but none of them works for me. Actually i'm adding <li>s dynamically. There maybe a problem. Please check,
#sps - a listbox
#add - a button
#splist - another listbox
#remove - a button
$(document).ready(function() {
$('#add').click(function(e) {
var selectedOpts = $('#sps option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#splist').append($(selectedOpts).clone());
$('ul').append('<li>' + selectedOpts.text() + 'Remove' + '</li>');
e.preventDefault();
});
$('#remove').click(function(e) {
var selectedOpts = $('#splist option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$(selectedOpts).remove();
e.preventDefault();
});
});
The .live() method of jQuery has been deprecated. You can get similar functionality using $('body') and delegating to .deletable like I did in the following code:
$('body').on('click', '.deletable', function(e){
e.preventDefault();
// this is the li that was clicked
$(this).parent().remove();
});
The preventDefault method is used to keep the link from loading a new page should there be something targeted in the href attribute. If you keep the same HTML structure as you have in your example, then you can simply take the anchor element (this) and grab the parent, then remove it from the DOM.
It would be wise to, instead of using $('body'), target the container for the .deletable anchors, which, in this case, would be $('ul'). The function would look like this:
$('ul').on('click', '.deletable', function(e){
e.preventDefault();
// this is the li that was clicked
$(this).parent().remove();
});
Using $('body') means that every event on the page would have to be filtered to see if it originated from a .deletable anchor. By scoping it to the ul preceding your li's, you limit the number of times your function is called increasing performance.
Some things first: if you're using jQuery 1.9, the .live() function is not anymore supported. Versions prior, that particular function is deprecated anyway, so you shouldn't really use it.
That being said, your syntax looks about correct. So I'm assuming that it's your hierarchy inside the handler function that's incorrect.
Something like this should work if you're trying to delete the parent <li>:
$('.deletable').on('click', function (e) {
// since you're working with a link, it may be doing wonky default browser stuff
// so disable that for now
e.preventDefault();
// then we delete the parent li here:
$(this).parent('li').remove();
});
If you really want to make that into a delegate signature, something like this should work:
$('form').on('click', '.deletable', function (e) {
// same banana
});
you can use $('a.deletable') selector ... this finds the <a> with class deletable.
u can go through the on delegate events too.. here is the docs
try this
$('a.deletable').on("click",function(){
alert("test"); // Debug
// Code to remove this <li> from <ul>
$(this).parent("li").remove();
});
if in case your <li> is added dynamically..
$(document).on("click",'a.deletable',function(){ .... //even more better if u replace the document with closest elements to a.deletable ..like $(form)
live() is depricated..
$('a.deletable').live("click",function(){
alert("test"); // Debug
$(this).parent('li').remove();
});

JQuery click on link not working

Ive the following code:
<script type="text/javascript">
$(document).ready(function(){
shortcut.add("Ctrl+Alt+N", function() {
$("#btnSave").click();
});
});
</script>
where btnSave is anchor element with ID btnSave, shortcut is from http://www.openjs.com/scripts/events/keyboard_shortcuts/ . If i change the line $("#btnSave").click(); to document.getElementById("btnSave").click() - all works fine. The question is why jquery implementation is not working in my case?
PS: made jsfiddle for my case: http://jsfiddle.net/0x49D1/WCmeU/
Here is the guy with similar problem: http://forums.asp.net/t/1591818.aspx
Instead of $("#btnSave").click(); try with $("#btnSave").trigger('click');
You can also use $("#btnSave")[0].click(); which is jquery equivalent to document.getElementById("btnSave").click();
Update:
It's not possible to simulate a user link click from javascript, for security reasons, all you can do is attach your own handler for click event and redirect based on the href of the link, like so:
$("#btnSave").bind('click', function() {
window.location.href = $(this).attr('href');
});
try this
<script type="text/javascript">
$(document).ready(function(){
shortcut.add("Ctrl+Alt+N", function() {
$("#btnSave").live('click',function(){
// do stuff here
});
});
}); </script>

jQuery: $(element).text() doesn't work

I am dynamically generating content - div's with links in them. Link should bring up a popup containing link's text when clicked (showMyText function). Instead I get an empty string :(
Why isn't this working? I've searched Stackoverflow and jQuery API and it should work.
function a(){
var div=document.createElement("div");
div.innerHTML='<a class="aClass" href="javascript:showMyText(this)">Link Text</a>';
var parent_div=document.getElementById('dinamicni_div');
parent_div.appendChild(div);
}
function showMyText(link){
var txt=$(link).text();
alert(txt);
}
If you're using jQuery to get the text() why not use it for everything else too?
function a() {
var $div = $("<div></div>");
var $a = $("<a></a>")
.attr("href", "#")
.addClass("aClass")
.text("Link text")
.appendTo($div);
$div.appendTo("#dinamicni_div");
}
$("#dinamicni_div").on('click', '.aClass', function() {
alert($(this).text());
});
Example fiddle
Change your code to:
div.innerHTML='<a class="aClass" onclick="showMyText(this)">Link Text</a>';
jsFiddle example.
I would take a slightly different approach and use the "live" method which will allow you to bind a click event to the dynamically created element once it is inserted into the DOM
$(document).ready(function(){
$('#dinamicni_div').html('<a class="aClass" href="#">Link Text</a>');
$(".aClass").live('click',function(){
alert($(this).text());
});
});
I find that text() stops working after the user manually edits the text area. val() continues to work as expected.

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>

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