SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Sep 2007
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help using focus() with dynamically created inputs

    I'm having an issue adding focus() to an input that is dynamically created with jquery. I'm still learning, so I've mixed in traditional js with my jquery code because it's easier for me to understand. Anyhow document.getElementById(name).style.backgroundColor="#72A4D2"; successfully changes the background of the input ID, but document.getElementById(name).focus(); does nothing. I know that this is the correct code because if I hard code an input into the form (which you can see I've commented out below, such as
    document.getElementById('password').focus(); it refocuses successfully on that input. Thus I'm stumped.

    Anyone know how to deal with this issue?

    JS:
    Code:
     
    $(function() {
    
    	var i = $('input').size() + 1;
    
    	$('a.add').click(function() {
    							  
    		$('<p>Username ' + i + ': <input type="text" id="user' + i + '" name="user' + i + '" onblur="javascript:checkl(this.name, this.value);"></p>').animate({ opacity: "show" }, "slow").appendTo('#inputs');
    		
    
    		i++;
    	});
    });
    
    function checkl(name, value){
    	var errors=new Array();
    	var x; 
      	var msg = "There were some problems...\n";
    	
    	if (value==="") {
      	errors['blank'] = "Field must not be blank";
    	}
      
      	for (x in errors)
     	 {
    	  msg += "\n"+errors[x];
      	 }
    
     	 if (!(x==undefined)){ 
      	alert(msg); 
    	document.getElementById(name).style.backgroundColor="#72A4D2"; //works, changed input background successfully
    	document.getElementById(name).focus(); // does NOT work, no focus
    	// document.getElementById('password').focus(); // successfully refocuses on hard coded 'password' input
    	}else{
    	document.getElementById(name).style.backgroundColor="";
    	}
    }
    HTML:
    Code:
    <a href="#" class="add" id="1"><img src="add.png" width="24" height="24" alt="add" title="add input" /></a> 
    <form id="target" name="target" action="post.php" method="post" onsubmit="return validate(this);">
    <div id="inputs">
    <!-- dynamically created inputs here -->
    </div>
    
    <!-- Password: <input type="password" id="password" name="password" size="10"> -->
    <input type="submit" value="Send">
    
    </form>

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,191
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Try this, personally i dont see why you don't just use this.focus() after javascript:checkl(this.name, this.value);

    Code JavaScript:
         if (!(x == undefined)){ 
            alert(msg); 
            $('#'+name).css('backgroundColor', '#72A4D2');
            $('#'+name).focus();
        } else {
            $('#'+name).css('backgroundColor', '');
        }

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    The blur code doesn't trigger in my web browser, so let's simplify things until we can get the code to work.

    Code javascript:
    $('a.add').click(function() {
        var i = $('input').size() + 1;
        $input = $('<input type="text" id="user' + i + '" name="user' + i + '">').blur(function () {
            console.log(this);
            checkl(this.name, this.value);
        });
        $p = $('<p>Username ' + i + ': </p>').append($input);
        $p.animate({ opacity: "show" }, "slow").appendTo('#inputs');
    });

    That code now triggers the blur event, so we can combine it together again now:

    Code javascript:
     
    $('a.add').click(function() {
        var i = $('input').size() + 1;
        $('<p>Username ' + i + ': </p>').append(
            $('<input type="text" id="user' + i + '" name="user' + i + '">').blur(function () {
                checkl(this.name, this.value);
            })
        ).animate({ opacity: "show" }, "slow").appendTo('#inputs');
    });

    Now that the blur event works, we can get to the meat of the problem.

    After some playing around with the focusing issue, it seems that when using tab to leave the input field there doesn't seem to be a problem.

    When using the mouse to click somewhere else on the screen, that seems to cause the lack of focus for me.

    Here's hoping that this helps somewhat.
    Last edited by paul_wilkins; Nov 14, 2010 at 23:57. Reason: s/blue/blur
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #4
    SitePoint Member
    Join Date
    Sep 2007
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    @SgtLegend - I wouldn't want to focus immediately after the onblur because everytime a user input valid data, that would just refocus on the field, even if everything was good. Or atleast I think that'd be the case.

    Apparently it was only a firefox issue, as IE & Chrome rendered correctly. Someone helped me out in another post and so if anyone else finds themselved with this firefox issue, it works when replacing

    Code:
    document.getElementById(name).focus(); // does NOT work, no focus
    with

    Code:
    setTimeout("document.getElementById('" + objField.id + "').focus()", 10); // works great in all browsers
    added objField to the onblur and function as so
    Code:
    function checkl(name, value, objField){
    ...
    Code:
    onblur="javascript:checkl(this.name, this.value, this);"
    It makes using this.name and this.value redundant but I'll just take those out later. Thanks for your help.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •