简体   繁体   中英

Set focus on onChange event of textbox

i want to set focus on textbox's itself on-change event if result is wrong. Suppose my textbox id is 'txtCaseCode'.

$('#txtCaseCode').change(function() {

     if(condition does not satsfy)
     {
        alert('Wrong ID');
        $('#txtCaseCode').focus();
     }

}

Bit it is not working. How will i achieve this?

Here is code after blur event attached:

 $('#txtCaseCode').change(function() {
     if(condition does not satsfy)
         {
            alert('Wrong ID');
            $('#txtCaseCode').blur(function(){
            $('#txtCaseCode').focus();//this is not working
            $('#txtCaseCode').val('Please click here.');//this is not working
             });
         }
     else
        {
           execute code;
        }
}

Change the event you're attaching to blur . This way, whenever the text-box loses focus, you can have the focus returned to it.

The change event occurs just before blur , and thus, calling focus() on a focused event does nothing.

try following:

 var $txt = $("#txtEmail").focus();

  $txt.blur(function(){   
    if(!validateEmpty(this)){
       $(this).focus();
    }    
 });

function validateEmpty(el){
    var flag = true,
         v = $(el).val();

    if(v == ""){
        alert("Can't Leave Blank");
        flag = false;
    }

   return flag;
}

working fiddle here: http://jsfiddle.net/4anAx/2/

I hope It Helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM