Skip to content Skip to sidebar Skip to footer

Jquery Works In Console But Not In .js File

$('ul#test a').click(function(){ $('this').closest('parent').find('textarea').val(this.getAttribute('href')); }); works in Google Chrome snippet but not loaded with Tampermonk

Solution 1:

Put your code inside ready function so the event will find the element in your selector since it will be executed just after the full load of the DOM :

$(function(){
   //Your code here
})

Try also the event delegation :

$(function(){
    $('body').on('click', '#test a', function(){
        $(this).closest('parent').find('textarea').val( $(this).attr('href') );
    });  
});

NOTE 1: The code works in the console because the DOM was fully loaded. NOTE 2: The $('this') should be $(this) instead & it will be better to use $(this).attr('href') rather than this.getAttribute('href').

Hope this helps.

Solution 2:

When you try the code in the console, the DOM is already done being built. If you have the code as you've shown it, before all of the HTML in the file, it will try to find the elements before the elements have been parsed into memory.

Place your code inside of a document.ready handler:

$(function(){
  $('ul#test a').click(function(){
   $('this').closest('parent').find('textarea').val(this.getAttribute('href')); 
  });
});

Post a Comment for "Jquery Works In Console But Not In .js File"