I wrote this simple script for validating non-empty input fields.
When, for instance, the form is sent and the input with the id ‘name’ is empty,
a short message will be displayed next to that element. The problem is that if
the form is sent one more time and that input is not empty anymore, doing this
$(element).nextAll().remove() will cause that the element with the id ‘phone’ disappears.
I just need to remove the message error and not all the other elements.
Please, suggest a short and easy way to solve that problem.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#formu").submit(function(){
validateInputText($("#name"),"Enter you name");
validateInputText($("#phone"),"Enter your phone number");
return false;
});
function validateInputText(inputText, errorMessage){
if($(inputText).val()==''){
setFieldAsNotValid(inputText, errorMessage)
}else{
removeErrorMessage(inputText)
}
}
function setFieldAsNotValid(element, errorMessage){
$(element).nextAll().remove();
$(element).after('<b>'+errorMessage+'</b>')
$(element).addClass('selected');
}
function removeErrorMessage(element){
$(element).nextAll().remove();
$(element).removeClass('selected');
}
});
</script>
</head>
<body>
<form id="formu">
name: <input type="text" id="name" />
phone: <input type="text" id="phone" />
<input type="hidden">
<input type="submit">
</form>
</body>
</html>
I created some code for you. It is not a direct answer for your question, but I think It is a better way to do what you want.
HTML:
CSS:
JavaScript:
With this code, you can improve your validation, creating new rules. There are some jQuery plugins that do the job, but since the plugin site of jQuery is under maintenance, I think you can use this approach. Note that I used some custom attributes to set the validation type, but you can use another approach, as creating a object that contains the validation constraints. I used “max” instead of maxlength since the latter is a valid input tag attribute. Anyway, the jsFiddle is here: http://jsfiddle.net/davidbuzatto/2N4yY/