Listen to objects click - javascript

I'm trying to listen to both "button" and "a" click, and then pass the value of the attribute "name" to a variable, I can't find what's wrong with my code:
$('a').click(function() {
var anchor;
anchor=$(this).attr('name');
$('#linkPressed').val(anchor);
});
$('button').click(function() {
var anchor;
anchor=$(this).attr('name');
$('#linkPressed').val(anchor);
});
Update: I have a PHP script that do something different according to the "linkPressed" value. Seemingly, this code is applicable also for <a> and <button> that don't have "name" attribute, which ruins my script. Is there a way to exclude the objects that don't have "name" attribute from the "click listener"?

To only select elements that have an attribute name, use the attribute selector:
$('a[name], button[name]').click(...);
// or
$('a, button').filter('[name]').click(...);

You can separate your selectors using comma ,. It's probably not working because you've initialize anchor variable two times:
$('a, button').click(function() {
var anchor;
anchor=$(this).attr('name');
$('#linkPressed').val(anchor);
});

You can bind the handler only to elements with name attributes:
$('a[name], button[name]').click(function() {
$('#linkPressed').val(this.name);
}

use multiple selector by the , at a one time it remove repetitive code
may be #linkPressed is a tag type not a input type at that time use text() at the palace of val()
$('a,button').click(function() {
var anchor;
anchor=$(this).attr('name');
$('#linkPressed').val(anchor);
});

I think this is it.
$("a, button").click(function() {
var anchor;
if($(this).attr("name") != undefined) {
anchor=$(this).attr('name');
$('#linkPressed').val(anchor);
}
});

Related

Removing an href value, if it exists using jquery

What would the best way to remove an href that has a specific value using jquery if it is found in the DOM.
$(document).ready(function () {
$('a').each(function () {
var hrefValue = $(this).attr("href")
if (hrefValue == '/remove/thehrefvalue?when=now') {
//remove only a href containing this specific value
}
});
});
Kind regards
Instead of iterating through every a, you can iterate through only as which have that particular href attribute by altering the selector string:
$('a[href="/remove/thehrefvalue?when=now"]').remove();
$('a[href="/remove/thehrefvalue?when=now"]').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
now
now
notnow
now
(Not entirely sure what you're looking for. If you wanted to remove the <a>s, use the code above - if you wanted to remove the attributes but leave the <a>s alone, use removeAttr('href') instead of .remove())
$(document).ready(function () {
$('a').each(function () {
if ($(this).attr("href") == '/remove/thehrefvalue?when=now') {
$(this).removeAttr("href");
}
});
});

Getting href value via jQuery

I want to get the value of href and hash of an a tag. When I do
$(document.body).on('click',"a",function(event){
console.log($(this));
});
I see an object with something like
[a.internalLink, context: a.internalLink, jquery: "1.10.2", constructor: function, init: function, selector: ""…]
0: a.internalLink
accessKey: ""
attributes: NamedNodeMap
...
hash: "#abc.1.2"
...
href: "http://www.example.com/page.html#abc.1.2
...
But when I tried to get the value by console.log($(this).href), it just doesn't work (prints out "undefined"). How can I get it?
If you want to refer to specific attributes of an element, you can use the attr function of jQuery:
$(document.body).on('click',"a",function(event){
console.log( $(this).attr("href") );
});
$( "a" )[0].href or $( "a" ).attr( "href" ).
$('body').on('click', 'a', function () {
console.log($(this).attr('href'));
});
$(document.body).on('click',"a",function(event){
console.log($(this).attr('href'));
event.preventDefault();
});
As per your code clicking "a" tag will give list of all the anchor tag objects in your page in an array for $(this). And each of these objects have jQuery specific properties (as this wrapped in jQuery) like href, hash etc.
So if you have only one anchor tag then you can use $(this)[0].href
But the more specific solution will be to use $(this).attr("href")
You can get both: full href or just the hash using this code:
$("body").on("click","a",function() {
var href = $(this).attr("href")
var hash = href.replace(/^.*?#/,'');
console.log(href + " - " + hash);
});
you can see a demo on JSFiddle.

jQuery - set data() variable from $(this).val()

I have an e-mail form on my website, with four fields. Three text inputs and a text area. Each field has a default value attribute which serves as its label. I would like these values to be automatically unset/reset on their element's focus and focusout events.
I have the following JavaScript/jQuery code, which creates this behaviour.
$('input,textarea').data('default', "bleh");
$('input,textarea').focus(function() {
if($(this).val() === $(this).data('default')) {
$(this).val('');
}
});
$('input,textarea').focusout(function() {
if ($(this).val() === '')
{
$(this).val($(this).data('default'));
}
});
My problem comes in the storing of the initial data('default') attribute. I had tried using .data('default', $(this).val())... but apparently that is illegal and $(this) is not recognized.
I have tried to find a clean jQuery way to iterate over each of the elements, but I can't seem to find one.
Is there an easy way, using jQuery, to achieve what I want?
Unless I'm mistaken, there's no reason to be setting data properties on the element, you can make use of the elements defaultValue property:
$('input, textarea').focus(function() {
if (this.value === this.defaultValue) {
this.value = '';
}
});
$('input, textarea').focusout(function() {
if (!$.trim(this.value).length) {
this.value = this.defaultValue;
}
});
Here's a fiddle
There is no this, because you're not in a callback. You'll have to iterate over each matched element, setting their default one at a time.
The "clean jQuery way" is simply with each:
$('input,textarea').each(function () {
$(this).data('default', $(this).val());
});
You need iterate through the input elements and then set the value to data using .each()
$('input,textarea').each(function(){
var $this = $(this);
$this.data('default', $this.val())
});

Javascript , jQuery - what have I done wrong?

$(document).ready(function () {
$("href").attr('href', 'title');
});
$('a[href$=.jpg]').each(function () {
var imageSrc = $(this).attr('href');
var img = $('<img />').attr('src', imageSrc).css('max-width', '300px').css('max-height', '200px').css('marginBottom', '10px').css('marginTop', '10px').attr('rel', 'lightbox');
$(this).replaceWith(img);
});
});
This is the jQuery code I have at the moment, which I want to change all links' href to the same as their title, before then embedding them in the page. Yet with the changing href to title bit in the code, it stops working. I'm new to Javascript so am definitely doing something wrong, just not sure what yet! Any help much appreciated!
Thank you guys
EDIT
This is the html that I want to change:
<p class="entry-content">Some interesting contenthttp://example.com/index.php/attachment/11</p>
You are changing it wrong, you are trying to select href elements instead of a.
This fix should do it:
$("a[title]").each(function() {
$(this).attr('href',$(this).attr('title'));
});
It will select all a elements with title and set the href with this value.
Here's a much more efficient way.
Since you're just replacing the <a> elements, there's really no need to change its href. Just select the <a> elements that end with jpg/jpeg, and use that attribute directly.
Example: http://jsfiddle.net/5ZBVf/4/
$(document).ready(function() {
$("a[title$=.jpg],[title$=.jpeg]").replaceWith(function() {
return $('<img />', {src:this.title, rel:'lightbox'})
.css({maxWidth: 300,maxHeight: 200,marginBottom: 10,marginTop: 10});
});
});​
Your .each() is outside the .ready() function.
You can accomplish the href change easily like this:
$(document).ready(function () {
$("a").attr('href', function() { return this.title; });
});
The .attr() method will accept a function where the return value is the new value of (in this case) href.
So the whole thing could look like this:
Example: http://jsfiddle.net/5ZBVf/3/
$(document).ready(function() {
$("a[title]").attr('href', function() { return this.title; })
.filter('[href$=.jpg],[href$=.jpeg]')
.replaceWith(function() {
return $('<img />', {src:this.href, rel:'lightbox'})
.css({maxWidth: 300,maxHeight: 200,marginBottom: 10,marginTop: 10});
});
});
This line:
$("href").attr('href','title');
Is finding all href elements and replacing their href attr with the string 'title'. Since there is no such thing as an href element, Try this instead:
// for every anchor element on the page, replace it's href attribute with it's title attribute
$('a').each(function() {
$(this).attr('href', $(this).attr('title');
});
Check this out: http://jsfiddle.net/TbMzD/ Seems to do what you want.
Note: $(document).ready() is commented because of jsfiddle, you actually need it in your code.
Try:
$("a").each(function () {
var $this = $(this);
$this.attr('href', $this.attr('title'));
});

jquery capturing text of selected id

If I have id's of the form: t_* where * could be any text, how do I capture the click event of these id's and be able to store the value of * into a variable for my use?
Use the starts with selector ^= like this:
$('element[id^="t_"]').click(function(){
alert($(this).attr('id'));
});
Where element could be any element eg a div, input or whatever you specify or you may even leave that out:
$('[id^="t_"]').click(function(){
alert($(this).attr('id'));
});
Update:
$('[id^="t_"]').click(function(){
var arr = $(this).attr('id').split('_');
alert(arr[1]);
});
More Info:
http://api.jquery.com/attribute-starts-with-selector/
var CurrentID = $(this).attr('id');
var CurrentName = CurrentID.replace("t_", "");
That should help with the repalce.
Try this:
// handle the click event of all elements whose id attribute begins with "t_"
$("[id^='t_']").click(function()
{
var id = $(this).attr("id");
// handle the click event here
});
$("[id^='t_']").click(function()
{
var idEnding = $(this).attr("id");
idEnding.replace(/\t_/,'');
});
Using the click event capture the ID that begins with t_, then replace that with nothing giving a capture the end of the ID value.

Categories