2

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/

1
  • 2
    <a id="test" onclick=(alert("hi")) >Alert</a> Commented Oct 13, 2013 at 5:59

4 Answers 4

2

Use a Vanilla Javascript!

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

Here is your jsfiddle

Sign up to request clarification or add additional context in comments.

2 Comments

@Mohsen try this jsfiddle.net/g5tCk :) I have changed few thigns though id to class but then indexing will have to be mentioned hence not generic solutions :)
@Mohsen: You can 1) have different id name 2) change id to class 3) use eq.
1

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');
}

Comments

0

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.