Search code examples
jqueryformserror-handlingappendto

add appropriate error message on submit jquery


I have a form that on submit I need to add an error message on the client-side using jQuery.

The form HTML (by others) is -

<div class="data">
<h3>Datos de acceso</h3>
<p class="email-login">
    <label for="email-login">Su correo electrónico</label>
    <input id="email-login" name="email-login" type="text" value="Su correo electrónico">
</p>
<p class="password-login">
    <label for="password-login">Elija una contraseña</label>
    <input id="password-login" name="password-login" type="text" value="Elija una contraseña">
</p>
<h3>Datos personales</h3>
<p>
    <label for="name">Nombre y apellidos</label>
    <input id="name" name="name" type="text" value="Nombre y apellidos">
</p>
<div class="data1">
    <p class="gender">
        <span class="female">
            <label for="gender-female">Mujer</label>
            <input id="gender-female" name="gender-female" type="radio" value="Mujer">
        </span>
        <span class="male">
            <label for="gender-male">Hombre</label>
            <input id="gender-male" name="gender-male" type="radio" value="Hombre">
        </span>
    </p>
    <p class="age select">
        <select>
            <option value="" selected="selected">Edad</option>
        </select>
    </p>
</div>
<div class="data2">
    <p class="country select">
        <select></select>
    </p>
    <p class="postal">
        <label for="postalcode">post code</label>
        <input id="postalcode" name="postalcode" type="text" value="post code">
    </p>
</div>
<div class="terms">
    <input type="checkbox" name="terms" value="Acepto las condiciones">
    <p class="checkbox"></p>
    <p>words<a href="#">?</a></p>
</div>
<p class="submit">
    <input class="button" type="submit" value="Conectar">
</p>

I've currently got this jQuery (which isn't working)

$(document).ready(function() {
    $('input').each(function() {
        var $this = $(this);
        if(!$this.val()) $this.addClass('error');
    });
});

The client now requires a different error message per form element. So an error for name, sex, postcode etc to be appended to the form. Is that possible? What have I done wrong in my jQuery for it not to work?


Solution

  • A good starting point will be to apply jQuery's submit method to your current jquery logic. They also have an example of input validation on that same API page.