0

I have error div that will appear when the form is submitted to the server,

<p>
    <input id="first_name" class="form-control" type="text" name="first_name" onkeyup="remove_error()" placeholder="First Name"> \
    <span id="error_first_name" class="err alert alert-danger">
        The first name may only contain letters.
        <br>
        The first name must be at least 2 characters.
    </span>
</p>

I have this code:

$("#first_name").keyup(function(e)
{
    $("#error_first_name").fadeOut();
});

I am planning to change it to

<input id="first_name" class="form-control" type="text" name="first_name" onkeyup="remove_error()"placeholder="First Name">

so that I can just call a function where it will remove the error in the same div with 'err' class. This is do-able if I will type in all input item 1 by 1, how can I make it to be a function where I can just call and remove the said div?

    function remove_error()
    {
        $(this).next(".err").fadeOut(); //get next div with err class and fadeout
    } 
rfpdl
  • 956
  • 1
  • 11
  • 35
  • I took the div tag I got from the bootstrap sample. if I switch it to span it becomes giberish – rfpdl Nov 01 '14 at 10:51

2 Answers2

1

It is better not to use inline event handlers. you can use a common class for the textboxes and do:

$(".commonClass").keyup(function(e){
  $(this).next(".err").fadeOut();
});

If you must use inline handler, then you should pass a reference to the element using this keyword:

<input id="first_name" class="form-control" type="text" name="first_name" onkeyup="remove_error(this)"placeholder="First Name">

And you can use it in the function:

 function remove_error(elm){
    $(elm).next(".err").fadeOut(); //get next div with err class and fadeout
} 

Read: Why is inline event handler attributes is a bad idea in modern semantic HTML?

Community
  • 1
  • 1
T J
  • 42,762
  • 13
  • 83
  • 138
  • this doesnt seem to work. $(".remove_err_onkeyup").keyup(function(e){ $(this).next('.err').fadeOut(); }); – rfpdl Nov 01 '14 at 11:02
0

you can just define a class for your element and it's validator , then use sibling to fadeout the validator element on keyup

$(".validate").keyup(function (e) {
    console.log($(this).siblings('.validator'));
    $(this).siblings('.validator').fadeOut();
});

check this fiddle

http://jsfiddle.net/mfarouk/6vgnfam7/

mfarouk
  • 644
  • 5
  • 14
  • I will be using this one. thanks for the other answers. – rfpdl Nov 01 '14 at 11:13
  • @Ponce `.siblings()` isn't the right choice for what you've shown in question. It'll search the entire parent for matching elements while in reality you just want to access the following element. Unnecessary `DOM` traversal is a bad practice. Also it doesn't answer how to use the inline handler or why you should not use it. BTW which answer to accept is entirely upto you. – T J Nov 01 '14 at 11:31