0

I have the following code which add a span on a json error:

 if (json['error']['firstname']) {
  $('#shipping-address      input[name=\'firstname\']')
 .after('<span class="error">' +    json['error']['firstname'] + '</span>');

1) But how add a class to the input field and to the Firstname (example: color:red;) if there is an json error and

2) then remove both (style classes and span class) if the field is filled in ?

Thanks in advance for helping.

4

3 回答 3

0

You can add the class to input like this:

if (json['error']['firstname']) {
    var $input = $('#shipping-address input[name="firstname"]');
    $input.addClass('someClass').after('<span class="error">' + json['error']['firstname'] + '</span>');
}

then remove both (style classes and span class) if the field is filled in

$('input[name="firstname"]').keypress(function (event) {
    if (this.value !== '') {
        $(this).removeClass('someClass');
        $(this).next('span.error').removeClass('error');
    }
});
于 2013-04-30T18:00:59.260 回答
0

Try creating the element like this before appending it to the desired element.

var span = $('<span></span>', {
    "class" : "yourClass",
    "style" : {
        "background" : "red"
    },
    "html"  : json['error']['firstname']      
});

If you want to add a class and a span on error, it should look something like this:

 if (json['error']['firstname']) {
     $('input[name="yourName"]').addClass('error');
     span.appendTo('input[name="yourName"]');
 }

Finally, create a listener for the input onchange to detect a valid value and remove class and span:

$('input[name="yourName"]').on('keyup', function() {
    if ($(this).val() != '') {
        $(this).removeClass('error');
        $(this).find('span').remove();
    }
});
于 2013-04-30T18:01:05.220 回答
0

Try this

if (json['error']['firstname']) 
{
  $('#shipping-address input[name=\'firstname\']').after('<span class="error">' +    json['error']['firstname'] + '</span>');
$('#shipping-address input[name=\'firstname\']').addClass('error_new');
}
于 2013-04-30T18:02:07.110 回答