jQuery function run when clicking on anchor with a specific value - javascript

I would like a function to run when a specific anchor with the `value="frb" is clicked.
This is the anchor
Accept
this is what i tried:
$('body').on('click', value[frb], function(e) {
e.preventDefault();
});
this doesnt work, i cant find any examples that use this, is it possible?

value is not valid attribute to anchor tag. Instead of that you can use data-value like following:
HTML
Accept
jQuery
$('body').on('click', 'a[data-value=frb]', function(e) {
e.preventDefault(); // prevent page reload
alert( this.href );
});
Working sample
Note:
Already #Musa mentioned about data attribute, but in his jQuery snippet used a[value=frb] which will not work.

The second parameter of .on() should be a selector string
$('body').on('click', 'a[value=frb]', function(e) {
e.preventDefault();
});
also a tag doesn't have a value attribute, you should use a data attribute instead
Accept

try this:
$(function(){
$('a[value=frb]').click(function(e) {
e.preventDefault();
});
});
It assigns the function to all anchors with the specified 'value' attribute.

working demo http://jsfiddle.net/KQy36/
OR http://jsfiddle.net/WP7JS/
API: http://api.jquery.com/on/
Oh by the way: http://www.w3schools.com/tags/tag_a.asp (To see valid a tag attribute)
Anyhoo, Hope this helps,
code
$('a[value="frb"]').on('click', function(e) {
alert('yeah wha?');
e.preventDefault();
});​
OR apart of another post below mine. :)
$('a').on('click', function(e) {
if ($(this).attr("value") === "frb") {
alert('yeah wha? I am frb');
e.preventDefault();
} else {
alert('not frb');
e.preventDefault();
}
});​

Since there is no value attribute for the link tag we need to make a change to the html:
<span class="frb">Accept</span>
Then add this to register the click event.
$(document).ready(function(){
$('span.frb').click(function(e) {
e.preventDefault();
});
});

Related

Javascript - Find <a> tag, where href attribute contains a string, prevent default event and override

I am having this code right now, which works just fine with links with an ID.
var buttonclick = document.getElementById("myLink");
buttonclick.addEventListener("click", function(event){
event.preventDefault(); window.location = 'facebook.com'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
google
What I want to do is get all links without an ID, just the ones which contain the world 'google' in the href attribute, and apply the same events further in my original code.
I have tried combining with jQuery, and all I managed to do is:
$('a[href*="google"]')
I am not sure how to combine it with the code above. Thank you in advance.
You can do it with document.querySelector(selector),
var buttonclick = document.querySelector('a[href*="google"]');
buttonclick.addEventListener("click", function(event){
event.preventDefault();
window.location = 'facebook.com'
});
If you want to target all the elements matches the selector then just use querySelectorAll instead of querySelector.
document.querySelectorAll('a[href*="google"]').forEach(function(button){
button.addEventListener("click", function(event){
event.preventDefault();
window.location = 'facebook.com'
});
});
Edited to use the function forEach belongs to nodeList object. It was inspired from #rory's answer.
You can achieve this by using a click() handler in your jQuery code. Try this:
$('a[href*="google"]').click(function(e) {
e.preventDefault();
window.location.assign('http://facebook.com');
});
If you'd prefer to stick with plain JS, then you can use querySelectorAll(), like this:
[].forEach.call(document.querySelectorll('a[href*="google"]'), function(el) {
el.addEventListener('click', function(e) {
e.preventDefault();
window.location.assign('http://facebook.com');
});
});

Only run function on element click with specific attribute

Now I would expect this function to only run when clicking on a <a data-popup="true"></a> element however it's running on every <a> click.
(function($) {
$(document).ready(function() {
$('a').data('popup', 'true').click(function(e) {
console.log($(this).data('popup'));
e.preventDefault();
});
});
})(jQuery);
The .data() method get/sets data associated with the element; it doesn't filter the elements like you are expecting. You are actually setting a key/value pair of data on all the anchor elements and then attaching an event listener to all the anchor elements. In other words, when you set data with the .data() method, the original jQuery object is returned (which means that the .click() method is still attaching a click event handler to all the originally selected anchor elements).
You are looking for an attribute selector. In this case, the selector a[data-popup="true"] will select anchor elements with a data-popup attribute value of true.
$('a[data-popup="true"]').click(function(e) {
console.log($(this).data('popup'));
e.preventDefault();
});
Below code will attach data for all existing a link in the code.
$('a').data('popup', 'true').click(function(e)
you may try this:
<a id="popid" data-popup="true"></a>
(function($) {
$(document).ready(function() {
$('#popid').click(function(e) {
console.log($(this).data('popup'));
e.preventDefault();
});
});
})(jQuery);
To check popup for all a link, you may try below.
(function($) {
$(document).ready(function() {
$('a').click(function(e) {
if ($(this).data('popup')){
console.log($(this).data('popup'));
e.preventDefault();
}
});
});
})(jQuery);
or
$('a[data-popup="true"]').click(function(e) {
console.log($(this).data('popup'));
e.preventDefault();
});

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

A click function not working

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();

Disable click if class ="X", jQuery

Im trying to build a tabbed content box, and im wondering if its possible that i can disable 1 link with a specific class, such as 'disabled'
I read somewhere about a function called preventDefault, would this work?
http://jsfiddle.net/Ssr5W/
You can disable click event by returning false. like,
$('#tabmenu a').click(function() {
return !$(this).hasClass('disabled');
});
Also, I've updated your fiddle: http://jsfiddle.net/Ssr5W/1/
EDITED
and of course, preventDefault would work :)
$('#tabmenu a').click(function(e) {
if($(this).hasClass('disabled'))
e.preventDefault();
});
fiddle: http://jsfiddle.net/Ssr5W/2/
$('.disabled').click(function(e) {
e.preventDefault() ;
}) ;
You can just check for the class on the element that was clicked on:
$('tabElement').click(function(){
if(this.hasClass('disabled'))
return;
//Your code here..
);
This won't interfere with other clikc-handlers you may have on your tab element

Categories