i have 2 txt fields named stuno and stuname . when i enter student no in the txtfield1 it pulls and shows the student name in the txtfield2. so here is what iam doing onload of the document iam putting the focus on txtfield1(stuno).If i dont put the focus it is pulling the Name very fine . IF i have the focus it is not pulling.Onload of the form i need to have focus on the txtfield1(stuno).Here is the code which i have please correct me if iam doing something wrong.
$(document).ready(function(){
$("#stuno").focus();
$("#stuno").change(function(){
if ( jQuery.trim( $( '#stuno' ).val() ) == '' ) {
$('#stuname').val( '' );
$( '#stuerr' ).text( 'Student Account Not Valid!' ) ;
}
else{
$.ajaxSetup ({cache: false});
$.getJSON("student.php",{'stuno' : $("#stuno").attr('value')},
function(data){
if(data[0].status){
var labelvalue = data开发者_开发技巧[0].label.split('-');
$("#stuname").attr("value",labelvalue[1]);
}else{
$('#stuname').val( '' );
$( '#stuerr' ).text(data[0].label);
}
if( $("#stuname").attr("value") ){
$( '#stuerr' ).text( '' ) ;
}
});
}
});
});
}
Try using keypress
instead of change
. Change is fired when you leave focus of the input or when a select box is changed. Keypress is fired whenever a key is pressed or released.
So instead of:
$("#stuno").change(function(){
use
$("#stuno").keypress(function(){
Not really an answer to your question.
You're changing between $ and jQuery which is a bit weird. Also, is there a reason why you're using $("#stuno").attr("value") instead of $("#stuno").val()?
Some browsers don't fire the onChange
event until focus is lost. Perhaps you'd want to do something like this instead:
jQuery(document).ready(function($){
$("#stuno").focus().keypress(function(e){
if(e.which === 13){ // if the enter key was pressed
e.preventDefault() // prevent the enter key from submitting the form
if ( $.trim( $( '#stuno' ).val() ) == '' ) {
$('#stuname').val( '' );
$( '#stuerr' ).text( 'Student Account Not Valid!' ) ;
}
else{
$.ajaxSetup ({cache: false});
$.getJSON("student.php",{'stuno' : $("#stuno").val()},
function(data){
if(data[0].status){
var labelvalue = data[0].label.split('-');
$("#stuname").val(labelvalue[1]);
}else{
$('#stuname').val( '' );
$( '#stuerr' ).text(data[0].label);
}
if( $("#stuname").val() ){
$( '#stuerr' ).text( '' ) ;
}
});
}
}
});
});
I've done a few things to your code. I changed all .attr('value',...)
calls to .val()
for consistency. And I've used the jQuery
variable on the outside of your ready function and ensure that the $
variable is in fact jQuery inside your ready function. And I've changed your change
handler to run on keypress
only if the key pressed was the Enter key.
精彩评论