Ayman El Temsahi
Ayman El Temsahi

Reputation: 2610

click on a link tag while using jquery ?

I have a link tag that doesn't contain a url, but instead it has javascript. I'm using jQuery and when I try the ".click()" function, it doesn't work. I searched through the website and found some answers but all of them open the "href" of the link tag and these answers won't be helpful in my case, here's an example of the code :

<button onclick="ClickMe();">CLick Me!</button>
<a id="test" href="javascript:alert('hi');">Alert</a>
<script>
    function ClickMe() {
        $("#test").click();
    }
</script>

This is a shared project and my ability to change the html of the page is very limited.

Here's the example : http://jsfiddle.net/Ayman_Mohamed/ygDmW/1/

Upvotes: 2

Views: 138

Answers (4)

Quantico
Quantico

Reputation: 2436

This might work

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("hi!");
}
</script>
</head>
<body>

<input type="button" onclick="myFunction()" value="Click Me" />

</body>
</html>

Upvotes: 0

Tats_innit
Tats_innit

Reputation: 34107

Working demo http://jsfiddle.net/sp3WR/

If you want to use href use it like this

Also all the answers above contains the click way as well.

Hope this helps the cause :)

code

function ClickMe() {
      window.location.href = $("#test").prop('href');
}

Upvotes: 1

Adil
Adil

Reputation: 148110

You are trying to fire click of anchor tag having id test which you havent binded you put alert on href not binding click, bind click event with href you will be able to fire it using click()

Live Demo

Html

<button onclick="ClickMe();">CLick Me!</button>&nbsp;&nbsp;
<a id="test" href="javascript:alert('Hi');" onclick="alert('href clicked')">Alert</a>

Javascript

function ClickMe() {
    $("#test").click();
}

Upvotes: 0

WhatisSober
WhatisSober

Reputation: 988

Use a Vanilla Javascript!

function ClickMe() {
   $('#test')[0].click();
}

Here is your jsfiddle

Upvotes: 2

Related Questions