3

I have an anchor and a text box as below:

 <div id="container">
        <input type="text" id="textBox" />       
        <a id="anchorTest" href="javascript: alert('inside anchorTest')">Click me</a>
    </div>

I'm trying to make the default button to the anchor when the enter key is clicked:

$(document).ready(function () {

            $('#anchorTest').click(function () {
                alert('clicked');
            });

            $('#container').keyup(function (e) {

                if (e.keyCode == 13) {                    
                    $('#anchorTest').triggerHandler('click');
                }
            });
        });

But the anchor href javascript is never called?

How to click the anchor using JQuery so that the href is also called?

I used the below code and it worked but is there any better way as it submits the form whereas I'd like to have a pure javascript code:

window.location = $('#anchorTest').attr('href');   

Thanks

The Light
  • 26,341
  • 62
  • 176
  • 258

3 Answers3

4

jQuery handles the click event on anchor tags in a 'special' way. See this question for further information - Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

From the question above -

I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.

Community
  • 1
  • 1
ipr101
  • 24,096
  • 8
  • 59
  • 61
0

Change your "triggerHandler" to just "trigger" and see if that resolves your issue.

I think triggerHandler bypasses the standard behavior and executes the "onclick" event handler in your case which is not set.

Dave G
  • 9,639
  • 36
  • 41
0
if (e.keyCode == 13) {                    
      $('#anchorTest').click();
}

Check from here http://jsfiddle.net/amBXV/

Sedat Başar
  • 3,740
  • 3
  • 25
  • 28