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

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.

Related

dynamic <a></a> doesn't run with jquery

I want to make a web site for a photos.
Inside a dynamic div created with a jquery function (.append) there is this anchor:
<a href='#' style='color:green;' id='"+this.foto_id+"' data-id='"+this.foto_id+"' class='modificaDataFoto modificaDataFoto"+this.foto_id+"'>Modifica</a>
The page is load normally and if I use the browser debugger I see all the HTML code including all dynamic data from database...
But if I try to set a class of the anchor in a jquery function it doesn't run:
$('.modificaDataFoto').bind('click', function(event) {
event.preventDefault();
var idFotoModifica= $(this).attr("data-id");
console.log(idFotoModifica);
$("dataFoto"+idFotoModifica).focus();
$("dataFoto"+idFotoModifica).css("color", "red");
$(this).attr("class", "modificaDataFotoConferma");
});
Why does that function not work?
.bind() only works on elements that are already present in the DOM. It's likely that you're trying to bind the click event to the element before the dynamic element exists.
There are two ways to fix this:
wait until after the <a> element has been appended to the document before running your $('.modificaDataFoto').bind(), or
Delegate the click event from a non-dynamic element (or the document itself):
$(document).on('click', '.modificaDataFoto', function() {
// this is essentially the same as your existing function; I've
// consolidated it a bit and removed the no-longer-needed preventDefault.
$("dataFoto" + $(this).attr("data-id")).css("color", "red").focus();
$(this).attr("class", "modificaDataFotoConferma");
}
Use this code:
$(document).on('click', '.modificaDataFoto', function(event) {
event.preventDefault();
var idFotoModifica = $(this).attr("data-id");
console.log(idFotoModifica);
$("dataFoto"+idFotoModifica).focus();
$("dataFoto"+idFotoModifica).css("color", "red");
$(this).attr("class", "modificaDataFotoConferma");
});
I'm not entirely sure if I understood your question but if you are trying to change the element's class name then you can simply do this:
$( this ).switchClass( "old class", "modificaDataFotoConferma", 1000, "easeInOutQuad" );
instead of
$(this).attr("class", "modificaDataFotoConferma");
You also have the .toggleClass()
EDIT:
You can also use removeClass() and then use the addClass().

How to dynamically update ID selector of a button in jQuery's .on() method?

I have a following piece of code
$('body').on('click', '#break-' + i, function(event) {
event.preventDefault();
var NowBreak = moment().format("HH:mm:ss");
console.log(NowBreak);
});
I'm trying to target an element with an ID which is dynamically generated in the other part of the code via jQuery's .append() method. So, I basically append a button with and ID of break+i where i is a variable containing some number, but when I try to access it as I do in the code above, it's not working. Why does it not work and how could I fix it? I suppose that I cannot use an expression as attribute with .on() method. Thank you.
you can try with this code
$('body').on('click', 'div[id^="break-"]', function(event) {
event.preventDefault();
var NowBreak = moment().format("HH:mm:ss");
console.log(NowBreak);
});
You can set the function directly to the target element using another jQuery selector: http://api.jquery.com/attribute-starts-with-selector/
$("[id^='break-']").click(function(event){
event.preventDefault();
var NowBreak = moment().format("HH:mm:ss");
console.log(NowBreak);
});

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

jquery click event reference with [this]

I have some hyperlinks and when user clicks on any of them I want to direct the user to that particular link. I am accessing the href attribute with jquery. Below is the code.
link1
link1
link1
Now I want to access the URL with jQuery I am using the below code:
$(document).ready(function() {
$('.class-name').click(function(){
var linkHref=$("this.class-name").attr('href');
alert(linkHref);
$('.redirect').attr('href',linkHref);
});
But I am getting "undefined" in the alert.
All your help is highly appreciated.
Change your code like this
$(document).ready(function() {
$('.class-name').click(function(){
var linkHref=$(this).attr('href');
alert(linkHref);
});
this is the object < a > that you selected with the click method. Thus you do not need to let jQuery search for the object based on class or id as previously. Hope this clarifies.
var linkHref=$(this).attr('href');
Your selector is wrong.
this is a special identifier that gets the context that your function is called in. It doesn't make sense to write "this"; the jQuery function has no way of knowing what your this is.
You probably want $(this).
You can also write $(this).find('.redirectLink'), but that isn't the code you're looking for.
In jQuery this refers to the current object in scope. In the case of a click event this refers to the hyperlink being clicked. But do not enclose it in quotes.
$(document).ready(function() {
$('.class-name').click(function(){
var linkHref=$(this).attr('href');
alert(linkHref);
$('.redirect').attr('href',linkHref);
});
});
you could shorten this to:
$(document).ready(function() {
$('.class-name').click(function(){
$('.redirect').attr('href',$(this).attr('href'));
});
});

JQuery click event, not working

I have the following scenario.
I have a index.php page with the following JQuery code included
jQuery(document).ready(function(){
jQuery('#sIMG img').click(function() {
var currentSRC = jQuery(this).attr('src');
var altSRC = jQuery(this).attr('title');
var imgID = jQuery(this).attr('id');
var cat = jQuery(this).attr('name');
/*Fade, Callback, swap the alt and src, fade in */
jQuery('#main').fadeOut('fast',function() {
jQuery('#main').load("detail.php?id="+imgID+"&category="+cat);
jQuery('#main').fadeIn('fast');
});
});
});
Now I have two div tags called #main and #right in the index.php page. When I click on a menu item right changes to a bunch of images, if I click on one of those images the above code should take effect and load into the main div, but it's just not working. the images are located within a div called sIMG. Any help will be appreciated
Try using live
jQuery('#sIMG img').live("click",function(){
});
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
jQuery('#sIMG img').on("click",function(){
});
I think what you're doing is setting "click" on the array that is return there. Try this:
jQuery('#sIMG img').each(function() {
jQuery(this).click(function() {
});
});
One of the reasons that the jquery click don't work is that you have dupplicates id's in the form.

Categories