Search code examples
jqueryinsertafter

jquery insertAfter or append question


I am playing around with validating form inputs.

For now I'm simply having fun with displaying a message after the input. I'm using the after() method to display simple text, and when I purposely make a mistake in the box I display the message perfectly.

However, if I purposely make a mistake again, it immediately adds the same message after the first error message.

Is there a method that replaces the original? I didn't want to try to add some more code to look for that original error message, delete it, and then insert the same message again.

I will if I have to, but I thought I'd ask first.

Here's my code:

<script language="javascript" type="text/javascript">
$(document).ready(function(){

  $("form#testform").submit(function(){
     if($("#fieldname1").val().length < 5){ $("#fieldone").after("<div>not enough characters</div>"); }
  });return false;


});
</script>

<form id="testform" method="post">         
<table>
    <tr>
        <td style="width:100px;">Field One:</td>
        <td><input type="text" name="fieldname1" id="fieldname1" /></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input type="submit" name="Submit" value="Submit" /></td>
    </tr>
</table>
</form>

Solution

  • I'd imagine doing something like this would be ideal:

    $('#fieldname1').change(function()
    {
         if($(this).val().length < 5 && $(this).parent().find('div').length == 0)
            $(this).after('<div>My Content</div>');
    });
    

    You look up the tree to the parent (<td>), and then if you find a div child, you know that message already exists. Else, add it.

    Now, I think a better choice would be to structure your HTML a bit differently, but that's a different discussion.