开发者

How do I display an error message using ajax next to a text box?

I just started PHP. I created a form in which there are three textboxes (name,email,age). Now suppose I fill deepak in textbox1 and开发者_开发知识库 then I press tab to go on next textbox but I keep it empty and then I press again tab and g in last textbox. As I move to third textbox, on the right side of textbox2 a error message should be displayed (plz fill email box). How I can do this? I know for this ajax will be used because I am not refreshing the page. Please give an example. Because once I get it I can apply this for all boxes...

                          Thanking You in Advance...


On the focus of the age input, you can text for the presence of text in the email field using jQuery.

Providied you have the following HTML

<input type="text" id="email" />
<p id="email-error-label"></p>
<input type="age" id="email" />

You can use the following JavaScript:

$('#age').focus(function (){
  email = $('#email').val();
  if(email.length() == 0)
  {
    $('#email-error-label').val('Please fill in email');
  }  
});

NB: I have not tested this code


Without digging in implementation [which depends if you are using a particular JS library and there is one example in the provided link] you should:

  1. Find the element you want to use as anchor
  2. create another element with DOM append child next to your anchor and fill it with the contents you want to display.

You can have a look at this example:

http://www.dustindiaz.com/add-remove-elements-reprise/


it is not ajax, all you need is manipulating dom with pure javascript.


Actually, it would be more better to check the email on the blur event, that is, when it loses focus (using jquery library):

$('#email').blur(function (){
email = $('#email').val();
if(email.length() == 0)
{
    $('#email-error-label').val('Please fill in email');  
}  
});

P.S.: Don't use only client-side code for validation, cause, if someone turns JS off in his/hers browser, the validation won't work.


Ajax is not always required in your program,

First we have to explain what is ajax, ajax is a very simple technology ,

  1. you have a php (or any server) page, that receive some input (*1) and generate some outputs (*2)
  2. a html+javascript page is required , that shows you the base page, then if required(a key press or any event) sends a request to php page (*1) ,then wait for a response from php page (*2) to execute a user defined function (*3), after receiving the result, the javascript event (*3) will update your page.

so in your problem if you want to check somethings special with user email address (check for previously registered user) you can use ajax, but if you just wants to check that the email is valid or not,you can use a simple javascript code

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜