Click anchor element using javascript function - javascript

I know this has been covered elsewhere on this site, as well as many others, but I just can't seem to figure it out.
I have an anchor tag that I use to show a lightbox form:
<a id="aNoData" href="#divNoData" class="fancybox">No Data</a>
I want to click it using a javascript function:
function fnNoData()
{
// This line works
alert("this line works");
// Neither of these lines work
$('#aNoData').click();
document.getElementById('aNoData').click();
}
I'm calling the function from my code behind, like this:
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "fnNoData()", true);
When I do this, the first line (the alert box) shows fine. However, the other two lines (to click the anchor tag) do not. The non-working lines work great if I put them in my $(document).ready block (the anchor clicks on page load). So it seems that the lines to click my anchor work fine, just not in my function.
Can anyone see what I'm doing wrong?

If you want to do click directly than you can use trigger
Check this hope this will helps you.
function fnNoData()
{
// This line works
alert("this line works");
//trigger
$('#aNoData').trigger('click');
//document.getElementById('aNoData').click();
}

jquery click event is expecting a function
(not tested)
$('#aNoData').on("click", function() {
console.log( "clicked the element with id aNoData );
});
in case you want to trigger the click(without the actual click), jquery has a function for that too:
http://api.jquery.com/trigger/

Quote from your comment
OK Patrick, thanks, and I did try putting the whole function inside my $(document).ready block, but it doesn't work at all there
You should not define the whole function inside $(document).ready(), instead define it outside and call it from inside the ready() function
Your original function
function fnNoData(){
// This line works
alert("this line works");
// Neither of these lines work
$('#aNoData').click();
}
Call it from ready()
jQuery(document).ready(function () {
fnNoData();
});
Hope this helps!

It took hours, but I finally brute-forced a solution.
As some repliers suggested, my code behind was trying to use the DOM before all elements were fully loaded. I got around that by changing the line in my code behind to this:
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "$(window).load(function() {fnNoData();});", true);

Related

JQuery click() event listener not working

im trying to get a lil project going but im stuck on a very annoying thing.
$(document).ready(function() {
$("#search-button").click(console.log('hello'))
});
as you can see im targeting a search button with the id search-button and as soon as i click it something should happen. in this case i put a console.log in to test if it works but it doesn't. it always logs it as soon as i load the page , not when i click the button i target. ... what am i doing wrong
if you need more info on this pls tell me i tried to keep it as simple as i could
ty for your help
O.k
The click handler needs a function argument, not just the console.log by itself. Try this:
$(document).ready(function() {
$("#search-button").click(function() {
console.log('hello');
});
});
Inside of .click should be a handler .click(handler) and the handler should be a function. The browser is reading the code and when it hits console.log('hello'), it does it! It's seeing .click etc, but it doesn't matter; it next sees console.log and does it.
Try
$(document).ready(function() {
$("#search-button").click(function() {
console.log('hello');
});
});
As others have mentioned, the click function requires its own callback function. You can also use this, without requiring the use of document:
$("#search-button").on('click', function() {
console.log('hello')
})
I hope You're using jQuery version 3 or up. if you use 3 or up jquery version the good practice is you use Document binding Example:
jQuery(document).on('click', '#search-button', function(event) {
//your Code here...
console.log('hello');
});

Why i can not trigger the jquery function?

This is a button to close the click but it fail and not work. I would like to know what is the tab ID since i did not think i assign one when i create a tab.
Thank you.
This is my attempt
js
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
html
<input type="button" id="closeTab" value="Cancel" class="submit"/>
I found my js code is working but the button can not trigger it? Why? thank you
latest try:
<script>
$(document).ready(function(){
$("#addlist").validate();
});
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
});
</script>
It still doesn't work so i think it is because the upper function ? How to fix this?
================================================================================
Also, are there any ways to clear my session in using this jquery function (what should i add for instance)?**Thanks
With javascript, you have to delay the execution of certain functions (like event handlers) until the page loads fully. Otherwise, it is attempting to bind a function to an element that doesn't yet exist. With jQuery, you can pass a function to jQuery to be executed on page load very easily like this:
$(function(){ /* code goes here */ });
So to use this with your code, you would do this:
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
});
This way, when the jQuery attempts to bind the function to #closeTab, it happens after the page has loaded (and after #closeTab exists).
Do you have any errors in the console?
Do you include jQuery before that click binding?
Try changing the window.parent.... to alert('clicked!'); and make sure you're actually getting there.
Also, make sure the click binding is inside of a:
$(document).ready(function(){
// here
});
A script can close only the windows it creates. It cannot close the tab which it didn't create.
To rephrase, cannot close tab only if unless but when created tab by script which is same that close window.
I hope this makes sense.
Maybe the form is submitted and the browser navigates to another URL before the code could run? Try replacing function() with function(e) and adding e.preventDefault(); to the beginning of the event handler.

jQuery select all elements with a common class

I want to handle a click event across a set of links so tried to approach this by adding a secondary class like following:
Test 1
Test 2
Test 3
Don't handle this one
Then tried this jquery selector to select the "external" class on links:
$('a.external').click(function(e) {
do something here...
});
However this isn't working like I expected. What's the right way to handle this? Should I just use a wildcard selector like the following or is there a better way?
$('[class^="someclass"]').click(function(e) {
....
});
What you have is exactly right (though the e probably isn't necessary in function(e) in your case).
Test 1
Test 2
Test 3
Don't handle this one
<script>
$('a.external').click(function(e) {
// will print the href in a javascript alert box
alert( $(this).attr('href') );
});
</script>
As far as I can tell the only possibility is that your <script> is actually above your <a> tags -- your script can't add the click listeners to the anchors because they wouldn't exist yet.
If so, you'll need to wrap the javascript in $(document).ready( function(){ /* code here */ });
Also, no need for the external class, just use the "select all absolute anchors, but not the ones linking to my domain" selector: $('a[href^="http://"]').not('[href^="http://mydomain.com"]')
I'm going to guess that your issue is that clicking the links actually makes it navigate somewhere? You need to tell the browser to ignore the normal link behavior. Otherwise your click function will run and then it will immediately navigate to the 'href' url. Also make sure this is all wrapped in a ready function.
$(function() {
$('a.external').click(function(e) {
// Do whatever
e.preventDefault();
});
});
I tried it out in jsFiddle and it works.
You have an extra parenthesis on the click() function.
Notice have your function(e) you have close parenthesis, remove that.
You should end up with this:
$('a.external').click(function(e) {
do something here...
});
try : http://jsfiddle.net/n6JJ3/
$('a.external').click(function() {
jQuery(this).css('background','red');
});​

jQuery Class selector not working

I'm struggling to make an alert come up when an anchor tag with a specific class is clicked inside of a div.
My html section in question looks like this...
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
The jQuery section is as follows..
$('.bar').click(function()
{
alert("CLICKED");
});
My problem is that I cannot get this alert to come up, I think that I'm properly selecting the class "next", but it won't pick it up for some reason. I've also tried almost everything on this page but nothing is working. If I don't try to specify the anchor tag i.e. $('#foo').click(function()... then it works, but there will be multiple anchor tags within this div, so simply having the alert executed when the div is clicked won't work for what I need. The website this is on is a search engine using ajax to send information to do_search.php. Within the do_search.php I make pagination decisions based on how many results are found, and if applicable, a next, previous, last, and first link may be made and echoed.
EDIT: I just figured it out, it was my placement of the .next function, since it wasn't created on the initial document load but instead after a result had been returned, I moved the .next function to the success part of the ajax function since that is where the buttons will be created if they need to be, now it works.
Try using the live() command:
$(".bar").live("click", function(){ alert(); });
Because you load your button via AJAX, the click event isn't binded to it. If you use the live() command, it will automatically bind events to all elements created after the page has loaded.
More details, here
.live is now deprecated and is the selected answer for this. The answer is in the comments in the selected answer above. Here is the solution that resolved it for me:
$(document).on('click','.bar', function() { alert(); });
Thanks to #Blazemonger for the fix.
You surely missed $(document).ready(). Your code should be:
$(document).ready(function(){
$('.bar').click(function()
{
alert("CLICKED");
});
});
Hope this helps. Cheers
Make sure you have included JQuery Library properly.
Make sure your script has written between $(document).ready() in short $(function(){ });
Demo : http://jsfiddle.net/W9PXG/1/
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
$(function(){
$('a.bar').click(function()
{
alert("CLICKED");
});
});

Jquery calling function on hashchange

I have 2 questions
I am using the hashchange plugin .... so I want to know would a function as below, be called everytime a hashchange occurs... because I have something like that in my code and the code function apparently doesnt seems to be called
$(document).ready(function()
{
// function here
});
On the other have if I remove the hashchange as in If i make http://abc.com/a.htm#http://abc.com/b.htm as http://abc.com/b.htm
the code works fine
the problem is the structure of my pages is a bit different .... here is the fiddle with the page structure that explains on a higher level what I am trying to achieve jsfiddle.net/vBKWd/9 ... on hash change jus the div c on my page 1 gets replaced by page 2 and vice versa .... and the js function that I have shown below is getting called only once and not after hashchange
Or is therre any way I can bind the function with the div so that whenever the div is replace the function get called?
No, a ready handler is only called on document ready, not on hash change. You should use the hashchange event for that, instead:
$(window).hashchange(function () {
// function here
});
Sample: http://jsfiddle.net/vBKWd/2/
In document ready wirte code below
$(window).bind('hashchange', function () {
//code here
});
use live in this case
$(document).ready(function()
{
$(selector).live(hashchange, function(){
// your code goes here
});
});

Categories

Resources