jQuery - anchor tag (click) doesn't create correct .focus()

Discussion in 'jQuery' started by PoPSiCLe, Mar 27, 2012.

  1. #1
    I have an anchortag up top, which links to a form on the bottom of the page - I'm trying to get focus on the first input in the form when I click the anchor-tag, but that seems to be a bit difficult.

    Currently, I have the following code:

    	$(function() {
    		$("#registernewanchor").click(function() {
    			$("#bookname").focus();
    		});
    		var id = "#" + $(location).attr('href').split('#')[1];
    		if (id != "#undefined") {
    			$("#bookname").focus();
    		};
    		});
    
    Code (markup):
    The first part of the code does NOT work - the second part works fine (hence, when the anchor-tag is already clicked, and you reload the page, it will focus on the input field just fine).

    I'm wondering what I need to do to get this to work properly?

    The page in question can be viewed here: http://www.junkfoodjunkie.no/booklist - if anyone want to see what I'm talking about, there's a guest account available (login: guest/guest) which will bring up the anchor tag and show what I'm talking about...
     
    PoPSiCLe, Mar 27, 2012 IP
  2. kuldipinfotech

    kuldipinfotech Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I'm not sure why you are facing problem.

    I have just check with below code and it's working as expected.

    $(document).ready(function(){
      $('.setFocusLink').bind('click', function(event){
        event.preventDefault();
        $('#focusHere').focus();
      });
    });
    Code (markup):
     
    kuldipinfotech, Mar 29, 2012 IP
  3. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    Yes. The preventDefault WORKS, but not the way I want it to. Point is, that when you add a book by using this way of doing it, the page refreshes, and you'll be left WITHOUT a focus, simply because the preventDefault prevents the url updating - hence the "#registernew" won't be part of the url anymore, and hence, there's nothing to really focus on when you refresh or add a book and the page refreshes. I've already tried that way, and it doesn't do what I want.

    Anyone else?
     
    PoPSiCLe, Mar 30, 2012 IP