nrs jayaram
nrs jayaram

Reputation: 3448

how to click an anchor tag from javascript or jquery

Have an anchor tag, trying to click it from the javascript but not responding, while loading the page it should go to next.php without click anchor tag manually.how can I archive this?

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="jquery-2.0.3.js"></script>
    <script type="text/javascript">
         alert("hai");
         $(document).ready(function() { $('#about').click(); });             
    </script>
</head>   
<body>
    <div>
         <a href="next.php" id="about">click here</a>
    </div>
</body>
</html>

Upvotes: 12

Views: 43802

Answers (5)

ndlinh
ndlinh

Reputation: 1365

$(document).ready(function() { $('#about').trigger('click'); });

Updated:

 $(document).ready(function() {  $('#about')[0].click(); });

Upvotes: 0

user786
user786

Reputation: 4374

Here is the code that can help you

$(document).ready(function() {


  $(document).ready(function() {
    $('a').trigger('click');
  });

})

function abc() {
  alert("");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="abc()">click me not</a>

If you want the recommended way then use this inside $(document).ready

window.location="where ever you want to go";

Upvotes: 1

Shaunak D
Shaunak D

Reputation: 20646

Use $('selector')[0], as $('selector') returns a jQuery object, so $('selector').click() will fire the click handler, while $('selector')[0].click() would fire the actual click.

$(document).ready(function () {
    $('#about')[0].click();  //$('#about').get(0).click();
});

Demo

Upvotes: 33

Kurenai Kunai
Kurenai Kunai

Reputation: 1902

If you want the page to go to next.php without clicking then place the window.location directly into $(document).ready(function() { });

Click() function is used when you want to trigger click event. ie. when you want to trigger some action when anchor tag is clicked.

<script>
   alert("hai");
   $(document).ready(function() { 
      window.location = 'next.php';  //If you wish the page to automatically go to next page on page load.
      $('#about').click(   // If you wish to do something clicking anchor
        function(){
           alert("Hello");
        }); 
      });
</script>

Upvotes: 0

PhuLuong
PhuLuong

Reputation: 537

You can not use javascript to fire click event

It should use

<script type="text/javascript">
       $(document).ready(function() { 
             document.location.href='/next.php'
       });
</script>

Upvotes: 3

Related Questions