开发者

Raising Errors on Failed Validation

开发者 https://www.devze.com 2022-12-17 21:19 出处:网络
Please check out the code HTML Code: First Name: <input type="t开发者_JAVA技巧ext" name="fname" id="fname" >

Please check out the code

HTML Code:

First Name: <input type="t开发者_JAVA技巧ext" name="fname" id="fname" >
<p id='p1'></p> 

Last Name: <input type="text" name="lname" id="fname" >

<input type="submit" name="submit" value="Submit" onclick="return validate_form();" >

Validation Code:

function validate_form()
{
    if ( document.form.fname.value == "" )
    {
        $('#p1').val("Please fill in fname");
        return false;
    }
}

I created a form in which there are two textboxes (fname,lname). Now suppose I kept textbox1 vacant and then I press tab to go on next textbox.As I move to second textbox, on the right side of textbox1 a error message should be displayed (plz fill fname box)

Plz check the coading and correct it..My code is not displayed here proeprly..how to copy - paste code here so that it can be visible proerly..I am new so plz...


The event you're looking to trigger on is called 'blur' and can be hooked up like this:

<input type="text" name="fname" id="fname" onblur="javascript:validate_form();" />

Or in jQuery:

$(function() {
  $('#fname').blur(validate_form);
});

Now the 'validate_form' function will be hooked in to the "blur" action on your fname field.

To post code on StackOverflow highlight the code portions of your questions and answers and click the button labeled "101010" to block it as code.

Also see theraccoonbear's comment on using .html() instead of .val().

EDIT: Added jQuery version and kept old input for up-voters.


Cryo mentioned that you want the onblur event, but I think you'd also need to modify the code that sets the error message to use the html() and not the val() method in jQuery. e.g.

$('#p1').html("Please fill in fname");


onclick="return validate_form();" >

Don't put form validation code on submit-onclick. It belongs on form-onsubmit. That way you're guaranteed the code will be called however the form is submitted.

if ( document.form.fname.value == "" )

You have an id on that control, might as well use document.getElementById('fname'), or, since you appear to be using jQuery, $('#fname').val(). Either of those is unambiguous, which accessing inputs directly from the document and form objects may not be.

$('#p1').val("Please fill in fname");

val() is for form fields not text content. You want .text('message').

0

精彩评论

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